I am trying to paste together text data from the same user that is currently organized in different rows by name:
df <- read.table(header = TRUE, text = 'name text
"katy" "tomorrow I go"
"lauren" "and computing"
"katy" "to the store"
"stephanie" "foo and foos"')
to have a result of:
df2 <- read.table(header=TRUE, text='name text
"katy" "tomorrow I go to the store"
"lauren" "and computing"
"stephanie" "foo and foos"')
suggestions?
We can use either data.table or dplyr or aggregate to paste the 'text' column grouped by 'name'. With data.table, we convert the 'data.frame' to 'data.table' (setDT(df)), before doing this.
library(data.table)
setDT(df)[, list(text=paste(text, collapse=' ')), by = name]
Using dplyr
library(dplyr)
df %>%
group_by(name) %>%
summarise(text=paste(text, collapse=' '))
Or with base R
aggregate(text~name, df, FUN= paste, collapse=' ')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With