更新时间:2022-11-18 23:39:51
你可以使用 ave
从 base
dat$mbirds <- with(dat, ave(birds, category, FUN=mean))
如果您要使用,请点击
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
这将是快速
Or you can use data.table
which would be fast
library(data.table)
setDT(dat)[,mbirds1:= mean(birds), by=category]