如何在 R 中的另一列的基础上粘贴行?

How to paste rows on the basis of another column in R?

我有如下数据框:


df = data.frame(ID = c("Text 1.1", "Text 1.2", "Text 1.3", "Text 1.4", "Text 2.1", "Text 2.2", "Text 2.3"), Text = c("Hello", "Hello World", "World", "Ciao", "Ciao Ciao", "SO will fix it", "World  is great"))

       ID            Text
1 Text 1.1           Hello
2 Text 1.2     Hello World
3 Text 1.3           World
4 Text 1.4            Ciao
5 Text 2.1       Ciao Ciao
6 Text 2.2  SO will fix it
7 Text 2.3 World  is great

我想实现这个:

       ID            Text
1 Text 1           Hello Hello World  World  Ciao
2 Text 2       Ciao Ciao SO will fix it World  is great

基本上,我想将每个 1.1,...,1.n 的文本粘贴到第二列; 2.1,...,2.n,等等

谁能帮帮我?

谢谢!

library(dplyr)
library(lubridate)

df %>%
  # extract everything before the "." in ID
  mutate(group = str_extract(ID, ".*(?=\.)")) %>%
  group_by(group) %>%
  # paste together
  summarize(Text = paste(Text, collapse = " "))
# # A tibble: 2 x 2
#   group  Text                                    
#   <chr>  <chr>                                   
# 1 Text 1 Hello Hello World World Ciao            
# 2 Text 2 Ciao Ciao SO will fix it World  is great

这个有用吗:

> library(dplyr)
> library(tidyr)
> df %>% separate(col = ID, into = c('ID','Sub-ID'), sep = '\.') %>% group_by(ID) %>% summarise(Text = paste0(Text, collapse = ' '))
`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 2 x 2
  ID     Text                                    
  <chr>  <chr>                                   
1 Text 1 Hello Hello World World Ciao            
2 Text 2 Ciao Ciao SO will fix it World  is great
>