lmcshane
lmcshane

Reputation: 1114

R paste data frame rows that belong to same id

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?

Upvotes: 6

Views: 2557

Answers (1)

akrun
akrun

Reputation: 887158

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=' ') 

Upvotes: 9

Related Questions