2014-09-01 52 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

相關問題