R - 连接/合并一个数据集中的行

时间:2014-10-10 08:35:40

标签: 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

如果文本2和文本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=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

我还希望能够使用两个变量的匹配元素组合行。

1 个答案:

答案 0 :(得分:1)

我认为你不能重塑或聚合,因为:

  1. 您有与相同键对应的重复行
  2. 每个键的值没有相同的值:您应该用缺少的值填充它
  3. 此处是使用by按键处理的手动尝试,rbind.fill将所有列表聚合在一起。每个by步骤都会创建一个以(Text2,Text3)为键的一行data.frame。

    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>