Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R paste data frame rows that belong to same id

Tags:

r

paste

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?

like image 403
lmcshane Avatar asked Mar 15 '23 02:03

lmcshane


1 Answers

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=' ') 
like image 117
akrun Avatar answered Mar 16 '23 15:03

akrun