Combining multiple rows into one single row in Dataframe in R

Suppose I have a dataframe, which looks like this.

| Category | Text |

| :--------: | :--------------------: |

| First | I am Groot. |

| First | We are Groot. |

| Second | The Dark Knight Rises. |

| Second | I am Batman. |

But we want to combine rows in column Text, which happens to have same value in category column, into one row and make it look like this.

| Category | Text |

| -------- | ------------------------------------ |

| First | I am Groot. We are Groot. |

| Second | The Dark Knight Rises. I am Batman. |

How do I do that?

library(tidyverse)

groot <- tibble(
  category = c("First", "First", "Second", "Second"),
  text = c("I am Groot.", "We are Groot.", "The Dark Knight Rises.", "I am Batman.")
)

groot %>% 
  group_by(category) %>% 
  summarise(text = str_c(text, collapse = " "))
#> # A tibble: 2 × 2
#>   category text                               
#>   <chr>    <chr>                              
#> 1 First    I am Groot. We are Groot.          
#> 2 Second   The Dark Knight Rises. I am Batman.

Created on 2021-10-25 by the reprex package (v2.0.1)

2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.