且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将自定义结果添加到现有的数据框架

更新时间: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]