How to add tapply results to an existing data frame [duplicate]

回眸只為那壹抹淺笑 提交于 2019-11-29 11:40:33

You can use ave from base

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

If you want to use 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

Or you can use data.table which would be fast

 library(data.table)
 setDT(dat)[,mbirds1:= mean(birds), by=category]

Here's an aggregate answer. Using a formula in its arguments makes it nice and simple.

> a <- aggregate(birds~category, dat, mean)
> cb <- cbind(dat, mean = a[,2][match(dat[[1]], a[,1])])
> head(cb)
#  category birds wolfs snakes  mean
#1      yes     3     9      7 3.200
#2       no     3     8      4 4.375
#3       no     1     2      8 4.375
#4      yes     1     2      3 3.200
#5      yes     1     8      3 3.200
#6       no     6     1      2 4.375

You can achieve that easily with dplyr package like this

dat <- dat %>% group_by(category) %>% mutate(mbirds=mean(birds))

More information about dplyr package can be found here.

You can find approaches with other packages in akrun's answer.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!