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

mig*_*ora 3 r dataframe tapply

我想将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)
Run Code Online (Sandbox Code Playgroud)

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

akr*_*run 6

您可以使用avebase

  dat$mbirds <- with(dat, ave(birds, category, FUN=mean))
Run Code Online (Sandbox Code Playgroud)

如果你想使用 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
Run Code Online (Sandbox Code Playgroud)

或者你可以使用data.table哪个会很快

 library(data.table)
 setDT(dat)[,mbirds1:= mean(birds), by=category]
Run Code Online (Sandbox Code Playgroud)