2014-10-10 22 views
2

我想知道如何使用R合并一组数据中的行。R - 在一个数据集中加入/合并行

目前我的数据是这样的:

Text 1  Text 2  Text 3  Text 4 
Bob  Aba   Abb   Abc 
Robert  Aba   Abb   Abc 
Fred  Abd   Abe   Abf 
Martin  Abg   Abh   Abi 

如果文本两个文本3都为两行相同(如行1 & 2)我想用更多的把它做成一排其他数据的列。

Text 1  Text 1a Text 2   Text 3  Text 4  Text 4a 
Bob   Robert  Aba   Abb   Abc  Abd 
Fred  NA   Abd   Abe   Abf  NA 
Martin  NA   Abg   Abh   Abi  NA 

我与数据连接两套独立的,并使用加入

join=join(Data1, Data2, by = c('Text2'), type = "full", match = "all") 

,但我不能工作,如何一组数据中做了重复的将它们合并类似的东西。

我认为有可能使用聚合,但我没有使用它之前,我的尝试是:

MyDataAgg=aggregate(MyData, by=list(MyData$Text1), c) 

但是当我尝试,我得到一个输出看起来像这样的总结:

1 -none- numeric        
1 -none- numeric        
2 -none- numeric 

或本上结构:

$ Initials    :List of 12505 
    ..$ 1 : int 62 
    ..$ 2 : int 310 
    ..$ 3 : int 504 

我也想能够排结合s使用两个变量的匹配元素。

+0

您能否提供一些更详细的信息?你需要重复多少列,只有'Text1'和'Text4'?你是否期望每个ID对有两个以上的副本(潜在列的数量只有两倍)? – ilir 2014-10-10 10:03:31

+0

在几乎所有情况下,只有两行是相同的 - 所以是列数的两倍。我并不担心在不太可能的情况下会丢失一些奇怪的数据,但有三行相同。但如果发生这种情况,它不得不中断 - 所以我不能通过对数据进行排序并依靠其他所有记录保持一致。还有比我的例子更多的变量。 – Wol44 2014-10-13 16:10:37

回答

1

我不认为你可以重塑或累计因为:

  1. 您有重复对应相同的密钥
  2. 您不必为每个键相同数量的值的行:你应与遗漏值

这里使用by通过钥匙来处理AA手动尝试,rbind.fill填充它聚合所有列表在一起。每个by步骤,正在创建具有(Text2,Text3)作为关键的单行数据帧。

do.call(plyr::rbind.fill,by(dat,list(dat$Text2,dat$Text3), 
    function(d){ 
    ## change all other columns to a one row data.frame 
    dd <- as.data.frame(as.list(rapply(d[,-c(2,3)],as.character))) 
    ## the tricky part : add 1 to a name like Text1 to become Text11 , 
    ## this is import to join data.frames formed by by 
    names(dd) <- gsub('(Text[0-9]$)','\\11',names(dd)) 
    ## add key to to the row 
    cbind(unique(d[,2:3]),dd) 
    })) 

Text2 Text3 Text11 Text12 Text41 Text42 
1 Aba Abb Bob Robert Abc Abd 
2 Abd Abe Fred <NA> Abf <NA> 
3 Abg Abh Martin <NA> Abi <NA> 
+0

谢谢你。但是,我仍然无法完成它的工作。除了更改数据和文本,还有其他任何我需要修改的部分吗? – Wol44 2014-10-13 16:00:03

+0

@ Wol44你会得到什么错误?请在该问题中添加一个'dput(head(data_frame))'。 – agstudy 2014-10-13 16:03:26