2011-09-30 66 views
3

我正在寫我的第一個 程序在R和作爲新手我有一些麻煩,希望你能幫助我。Aggregate R sum

我有一個數據幀是這樣的:

> v1<-c(1,1,2,3,3,3,4) 
> v2<-c(13,5,15,1,2,7,4) 
> v3<-c(0,3,6,13,8,23,5) 
> v4<-c(26,25,11,2,8,1,0) 
> datos<-data.frame(v1,v2,v3,v4) 
> names(datos)<-c("Position","a1","a2","a3") 

> datos 
    posicion a1 a2 a3 
1  1 13 0 26 
2  1 5 3 25 
3  2 15 6 11 
4  3 1 13 2 
5  3 2 8 8 
6  3 7 23 1 
7  4 4 5 0 

我需要的是總結的數據a1a2a3(在我的實際情況,從a1a51)由Position分組。我試着用功能aggregate(),但它只適用於手段,而不是和數,我不知道爲什麼。

在此先感謝

回答

7

這對於plyr庫很簡單。

library("plyr") 
ddply(datos, .(Position), colwise(sum)) 

如果你有一個不應該被平均附加的非數字列,您可以使用

ddply(datos, .(Position), numcolwise(sum)) 
+0

嗨布萊恩,我做了一個證明,它似乎是我所需要的。不過,我需要用我的真實數據來檢查一些事情。我會告訴你。感謝您的幫助! –

+0

我檢查過它,這正是我需要的。非常感謝! –

15

你需要告訴聚集函數使用金額,作爲默認的是,它讓每個類別的平均值。例如:

aggregate(datos[,c("a1","a2","a3")], by=list(datos$Position), "sum")