2014-09-01 50 views
3

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

我想补充每个类别的平均数据帧为一列。 我用:tapply(dat$birds, dat$category, mean)来获得每个类别的平均值,但是我没有找到一种方法将它添加到数据集中,以至于在新的列中我将具有相关类别的均值。

回答

6

您可以使用avebase

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

如果你想使用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 

或者你可以使用data.table这将是快速

​​
+0

谢谢@akrun它的工作.. – 2014-09-01 11:48:44

+0

@migdal menora很高兴为你工作 – akrun 2014-09-01 11:49:22

1

您可以dplyr包实现,很容易像这样

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

更多dplyr包的信息可以发现here

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

+0

非常感谢@iugrina,但是当我写名字(dat)时,我没有得到新变量“mbirds”。我如何将它添加到原始数据框中?我还有两个问题:%>%的含义是什么?另外,你有没有任何想法如何做到这一点,而不需要dplyr包? – 2014-09-01 11:45:11

+0

我会调整我的答案 – iugrina 2014-09-01 11:52:30

3

这里是一个aggregate答案。在它的参数中使用公式使得它很好而且简单。

> 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 
+0

谢谢理查德.. – 2014-09-01 12:14:55