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

R 如何将tapply结果添加到现有数据框,r,dataframe,tapply,R,Dataframe,Tapply,我想将tapply结果作为新列添加到原始数据框中 这是我的数据框: dat <- read.table(text = " category birds wolfs snakes yes 3 9 7 no 3 8 4 no 1 2

我想将
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)

dat使用这样的包,您可以轻松实现这一点

dat%按(类别)分组%>%变异(mbirds=mean(birds))

可以找到关于dplyr包的更多信息


你可以在akrun的回答中找到其他软件包的方法。

你可以使用
ave
from
base

  dat$mbirds <- with(dat, ave(birds, category, FUN=mean))
或者你可以使用
data.table
,这会很快

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

下面是一个
聚合
答案。在它的参数中使用公式可以使它变得很好和简单

> 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
>断路器头部(cb)
#鸟类、狼、蛇是什么意思
#1是3973200
#2号3 8 4.375
#3号1号2号8 4.375
#4是123200
#5是183.200
#6号6 1 2 4.375

非常感谢@iugrina,但是当我写名字(dat)时,我没有得到新变量“mbirds”。如何将其添加到原始数据框中?我还有两个问题:%>%的含义是什么?另外,您是否知道如何在不需要dplyr包的情况下执行此操作?我将调整我的答案
> 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