2013-03-08 98 views
8

我有一個數據幀DF這樣的:如何在聚合數據框之後將rownames列表作爲值?

type V1 V2 
1 A bla bla 
2 A bla bla 
3 B bloo bla 
4 B bloo bla 
5 C moo bloo 
6 C moo bloo 

目前我融化/施放得到這樣的:使用這些命令

type bla bloo moo 
A 4 0 0 
B 2 2 0 
C 0 2 2 

library(reshape) 
melted <- melt(df, id='type') 
count <- function(x) { 
    length(na.omit(x)) 
} 
casted <- cast(melted, type~value, count) 

但不是計數/總結,我想要得到原始rownames的列表。是這樣的:

type bla bloo moo 
A 1,2 0 0 
B 3,4 3,4 0 
C 0 5,6 5,6 

其中對於BLA,布盧和MOO每個值是從原始數據幀獨特rownames的列表。

任何人都可以幫忙嗎?

回答

11
library(reshape2) 
df <- read.table(text="type V1 V2 
1 A bla bla 
2 A bla bla 
3 B bloo bla 
4 B bloo bla 
5 C moo bloo 
6 C moo bloo") 

df$id <- rownames(df) 

melted <- melt(df, id=c('type','id'),measure.vars=c("V1","V2")) 

fun <- function(x) paste(unique(x),collapse=",") 

dcast(melted,type~value,fun,value.var="id",fill="0") 

# type bla bloo moo 
#1 A 1,2 0 0 
#2 B 3,4 3,4 0 
#3 C 0 5,6 5,6 
+3

小挑剔:也許使用'fill ='0'來完全匹配OP的期望輸出...? – joran 2013-03-08 17:04:01

+0

@joran完成。感謝提示。 – Roland 2013-03-08 17:05:19

+0

令人驚歎!感謝羅蘭和喬蘭:-) – 2013-03-08 17:10:21

相關問題