我希望能够根据数据框中不同列的值(author
),合并/粘贴 (paste(c(...), collapse=" ")
) 字符串。我正在寻找一种高效的方法来完成这个任务。
df <- data.frame(author = c("Shakespeare",
"Dante",
"Proust",
"Shakespeare",
"Dante",
"Proust",
"Shakespeare"),
text = c("Put the wild waters in this roar, allay them",
"Ma tu perche' ritorni a tanta noia?",
"Longtemps, je me suis couché de bonne heure",
"The very virtue of compassion in thee",
"Pensa oramai qual fu colui che degno",
"Quelle horreur! me disais-je",
"She said thou wast my daughter; and thy father"))
最终结果应该是:
result <- c("Put the wild waters in this roar, allay them The very virtue of compassion in thee She said thou wast my daughter; and thy father",
"Ma tu perche' ritorni a tanta noia? Pensa oramai qual fu colui che degno",
"Longtemps, je me suis couché de bonne heure Quelle horreur! me disais-je")
names(result) <- c("Shakespeare","Dante","Proust")
result
# Shakespeare
# "Put the wild waters in this roar, allay them The very virtue of compassion in thee She said thou wast my daughter; and thy father"
# Dante
# "Ma tu perche' ritorni a tanta noia? Pensa oramai qual fu colui che degno"
# Proust
# "Longtemps, je me suis couché de bonne heure Quelle horreur! me disais-je"
我猜我应该使用apply
函数族中的某个函数。类似这样:
apply( df[??? , 2 , paste , collapse = " " )
但我不确定如何满足条件并获得与粘贴的字符串对应的作者姓名作为结果...
array <- tapply(df$text, df$author, paste, collapse = " ") result <- as.character(array) names(result) <- names(array)
- CptNemoaggregate(text~author, df, paste, collapse=" ")
同样如此。 - Tyler Rinker