2014-12-07 42 views
2

我有這樣的數據幀:如何按組「起源 - 目的地」數據框進行求和?

df<-data.frame(Origin=c(1,1,1,2,2,3,3,3), 
       Var= c(2,4,1,3,5,6,2,1), 
       Desti= c(2,2,3,2,1,2,1,3)) 

我想獲得的Var的總和,爲Origin每個值,由Desti(Out.x)分組並通過Origin(In.x)。結果將爲df

Out.1 Out.2 Out.3 In.1 In.2 In.3 
1  0  6  1 0 5 2 
2  5  3  0 6 3 6 
3  2  6  1 1 0 1 

任何想法?

回答

4

可能這有助於

res <- cbind(xtabs(Var~., df), xtabs(Var~Desti+Origin, df)) 
colnames(res) <- paste(rep(c("Out", "In"), each=3), 1:3, sep=".") 
res 
# Out.1 Out.2 Out.3 In.1 In.2 In.3 
#1  0  6  1 0 5 2 
#2  5  3  0 6 3 6 
#3  2  6  1 1 0 1 

或者,上面可以簡單求

r1 <- xtabs(Var~., df) 
res <- cbind(r1, t(r1)) #change the `column names` accordingly 

或者使用reshape2

library(reshape2) 
res1 <- cbind(acast(df, Origin~Desti, value.var='Var', sum), 
       acast(df, Desti~Origin, value.var='Var', sum)) 
colnames(res1) <- colnames(res) 
+0

課程的轉!很好,謝謝 – DJack 2014-12-07 12:26:27

相關問題