R: Merge of rows in same data table, concatenating certain columns

后端 未结 2 1236
北荒
北荒 2020-12-30 08:40

I have my data table in R. I want to merge rows which have an identical customerID, and then concatenate the elements of other merged columns.

I want to

2条回答
  •  有刺的猬
    2020-12-30 08:54

    Maybe not the best solution but easy to understand:

    df <- data.frame(author=LETTERS[1:5], title=LETTERS[1:5], id=c(1, 2, 1, 2, 3), stringsAsFactors=FALSE)
    
    uniqueIds <- unique(df$id)
    
    mergedDf <- df[1:length(uniqueIds),]
    
    for (i in seq(along=uniqueIds)) {
        mergedDf[i, "id"] <- uniqueIds[i]
        mergedDf[i, "author"] <- paste(df[df$id == uniqueIds[i], "author"], collapse=",")
        mergedDf[i, "title"] <- paste(df[df$id == uniqueIds[i], "title"], collapse=",")
    }
    
    mergedDf
    #  author title id
    #1    A,C   A,C  1
    #2    B,D   B,D  2
    #3      E     E  3
    

提交回复
热议问题