gpt4 book ai didi

r - 如何将 tapply 结果添加到现有数据框

转载 作者:行者123 更新时间:2023-12-01 08:28:59 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Calculating statistics on subsets of data [duplicate]

(3 个回答)


5年前关闭。




我要加tapply结果到原始数据框作为一个新列。

这是我的数据框:

 dat <- read.table(text = " category birds    wolfs     snakes
yes 3 9 7
no 3 8 4
no 1 2 8
yes 1 2 3
yes 1 8 3
no 6 1 2
yes 6 7 1
no 6 1 5
yes 5 9 7
no 3 8 7
no 4 2 7
notsure 1 2 3
notsure 7 6 3
no 6 1 1
notsure 6 3 9
no 6 1 1 ",header = TRUE)

我想将每个类别的平均值作为列添加到数据框中。
我用过: tapply(dat$birds, dat$category, mean)获得每个类别的平均值,但我没有找到将其添加到数据集中的方法,以至于在新列中我将获得相关类别的平均值。

最佳答案

您可以使用 ave来自 base

  dat$mbirds <- with(dat, ave(birds, category, FUN=mean))

如果您想使用 tapply
  mbirds1 <- with(dat, tapply(birds, category, mean))
dat$mbirds1 <- mbirds1[match(dat$category,names(mbirds1))]

head(dat)
# category birds wolfs snakes mbirds mbirds1
#1 yes 3 9 7 3.200 3.200
#2 no 3 8 4 4.375 4.375
#3 no 1 2 8 4.375 4.375
#4 yes 1 2 3 3.200 3.200
#5 yes 1 8 3 3.200 3.200
#6 no 6 1 2 4.375 4.375

或者您可以使用 data.table这会很快
 library(data.table)
setDT(dat)[,mbirds1:= mean(birds), by=category]

关于r - 如何将 tapply 结果添加到现有数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25604648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com