2012-07-18 57 views
1

基于R重复的数据,如果我有一个2列数据帧:查找指数和字符串一起

meta <- c(1,2,2,3,4,4,4,5) 
value <- c("a","b","c","d","e","f","g","h") 
df <- data.frame(meta,value) 
df 
    meta value 
1 1  a 
2 2  b 
3 2  c 
4 3  d 
5 4  e 
6 4  f 
7 4  g 
8 5  h 

我怎么会去反复用分隔符(如||)“值”组合“元”,使得所得到的数据帧看起来像:

meta value 
1 1  a 
2 2 b||c 
3 3  d 
4 4 e||f||g 
5 5  h 

谢谢!

回答

2

使用plyr包的以下作品

library(plyr) 
> ldply(split(df,meta),function(x){paste(x$value,collapse="||")}) 
    .id  V1 
1 1  a 
2 2 b||c 
3 3  d 
4 4 e||f||g 
5 5  h 

> ddply(df,.(meta),function(x){c(value=paste(x$value,collapse="||"))}) 
    meta value 
1 1  a 
2 2 b||c 
3 3  d 
4 4 e||f||g 
5 5  h 

,如果你想保留名称

2

我希望你不喜欢一个套:data.frame( meta = unique(df $ meta),value = sapply(unique(df $ meta),function(m){paste(df $ value [which(df $ meta == m)],collapse =“||”)} ))

> data.frame(meta=unique(df$meta), value=sapply(unique(df$meta), function(m){ paste(df$value[which(df$meta==m)],collapse="||") }) ) 
    meta value 
1 1  a 
2 2 b||c 
3 3  d 
4 4 e||f||g 
5 5  h 
4

略有不同,比较瘦,在基地:

y <- split(df$value, df$meta) 
data.frame(meta=names(y), value=sapply(y, paste, collapse="||")) 

或更简单:

aggregate(value~meta, df, paste, collapse="||") 
+0

+1骨料 – A5C1D2H2I1M1N2O1R2T1 2012-07-19 02:58:15

0

这里是另一种方式......

uni.meta <- unique(df$meta) 
    list <- lapply(1:length(uni.meta),function(x) which(df$meta==uni.meta[x])) 
    new.value <- unlist(lapply(1:length(list),function(x) paste(df$value[list[[x]]],collapse="||"))) 
new.df <- data.frame(uni.meta,new.value) 

new.df 
    uni.meta new.value 
1  1   a 
2  2  b||c 
3  3   d 
4  4 e||f||g 
5  5   h