根据作者将字符串拼接起来

3

我希望能够根据数据框中不同列的值(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 = " " )

但我不确定如何满足条件并获得与粘贴的字符串对应的作者姓名作为结果...

1个回答

1

tapply 的工作方式与您预期的几乎完全相同:

tapply(df$text, df$author, paste, collapse = " ")

一种更时髦的解决方案是使用 dplyr
library(dplyr)
df %>% group_by(author) %>% summarize(passage = paste(text, collapse = " "))

array <- tapply(df$text, df$author, paste, collapse = " ") result <- as.character(array) names(result) <- names(array) - CptNemo
1
aggregate(text~author, df, paste, collapse=" ") 同样如此。 - Tyler Rinker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接