11

R にデータ テーブルがあります。同一の を持つ行をマージしcustomerID、他のマージされた列の要素を連結したいと考えています。

私はこれから行きたい:

   title  author customerID
1 title1 author1          1
2 title2 author2          2
3 title3 author3          1

これに:

           title           author Group.1
1 title1, title3 author1, author3       1
2         title2          author2       2
4

2 に答える 2

14

このaggregate関数は、解決策を見つけるのに役立ちます。

dat = data.frame(title = c("title1", "title2", "title3"),
                 author = c("author1", "author2", "author3"),
                 customerID = c(1, 2, 1))
aggregate(dat[-3], by=list(dat$customerID), c)
#   Group.1 title author
# 1       1  1, 3   1, 3
# 2       2     2      2

stringsAsFactors = FALSEまたは、データ フレームを作成しているときに追加することを確認してください。データがすでに因数分解されている場合は、dat[c(1, 2)] = apply(dat[-3], 2, as.character)最初にそれらを文字に変換するなどの方法を使用してから、次のようにします。

aggregate(dat[-3], by=list(dat$customerID), c)
#   Group.1          title           author
# 1       1 title1, title3 author1, author3
# 2       2         title2          author2
于 2012-07-06T17:06:21.783 に答える
3

おそらく最善の解決策ではありませんが、理解しやすいです:

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
于 2012-07-06T16:56:42.100 に答える