-3

I got a table like this:

id     words
1     I like school.
2     I hate school.
3     I like cakes.
1     I like cats.

Here's what I want to do, joining the strings in each row according to id.

id    words
1    I like school. I like cats.
2    I hate school.
3    I like cakes.

Is there a package to do that in R?

Lucia
  • 615
  • 1
  • 9
  • 16

1 Answers1

1

We can paste the 'words' together grouped by 'id'. This can be done with any of the group by operations. One way it is data.table. We convert the 'data.frame' to 'data.table' (setDT(df1)) and then do the operation was mentioned above.

# install.packages(c("data.table"), dependencies = TRUE)
library(data.table)
setDT(df1)[, list(words = paste(words, collapse=' ')), by = id]

A base R operation would be to use aggregate

aggregate(words~id, df1, FUN= paste, collape=' ')
akrun
  • 874,273
  • 37
  • 540
  • 662