提问者:小点点

多行相同的行到一行,但数量不同的行[重复]


我有这样的数据:

我想将其转换为如下数据集:

有可能吗?

谢谢你。


共1个答案

匿名用户

在我的评论中添加一些细节:

library(dplyr)

data <- tibble::tribble(
  ~id,        ~word,
   1L,     "arrive",
   1L,        "bus",
   1L,       "stop",
   1L,       "time",
   1L,      "beard",
   1L,    "bearded",
   1L,       "sits",
   2L,     "whilst",
   2L,      "begin",
   2L,      "argue",
   2L,       "seat",
   2L,       "time",
   2L,     "police",
   3L,    "officer",
   3L,      "walks",
   3L, "intervenes"
  )

data %>% 
  group_by(id) %>% 
  mutate(word = paste0(word, collapse = " ")) %>% 
  slice(1) %>% # Take the first line from each group
  ungroup()

或者更好(所以你不需要切片):

data %>% 
  group_by(id) %>% 
  summarise(word = paste0(word, collapse = " "))