0

As the initial dataframe:

structure(list(text = c("test", "text", "section", "2", "sending"
), id = c(32, 32, 41, 41, 41)), class = "data.frame", row.names = c(NA, 
-5L))

How is it possible to make from long to wide format using the same id to put in the same row the content of text column separated by space?

Example output:

id text
32 test text
41 section 2 sending
demia
  • 39
  • 5

2 Answers2

2

You can try this:

library(tidyverse)

df %>%
  group_by(id) %>%
  mutate(text = paste(text, collapse = " ")) %>%
  slice(1)

# A tibble: 2 x 2
# Groups:   id [2]
  text                 id
  <chr>             <dbl>
1 test text            32
2 section 2 sending    41

tamtam
  • 3,541
  • 1
  • 7
  • 21
2

You can aggregate from the {stats} package and use paste as your aggregating function:

aggregate(text ~ id, FUN = paste, collapse = " ", data = df)

#>   id              text
#> 1 32         test text
#> 2 41 section 2 sending
anddt
  • 1,589
  • 1
  • 9
  • 26