Paste row together based on author

I want paste(c(...), collapse=" ")

to concatenate / insert rows ( ) into dataframe based on value ( author

) in another column. I am looking for an efficient way to do this.

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"))

      

And the end result should be

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" 

      

I think I need to use some function from the family somehow apply

. Something like

apply( df[??? , 2 , paste , collapse = " " )

      

but I'm not sure how to pass this condition and then get as the result the name of the author that the inserted rows match ...

+3


source to share


1 answer


tapply

works more or less exactly as you'd expect:

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

      



A more efficient solution would be to use dplyr

library(dplyr)
df %>% group_by(author) %>% summarize(passage = paste(text, collapse = " "))

      

+1


source







All Articles