0

我有一个看起来像这样的数据框。

df <- data.frame(year = c(1978, 1978, 1979, 1979), bus = c("29C", "12B", "25G", "27C"))

我希望为 year 列创建唯一值并合并 bus 列的值。预期输出如下

# year  bus
# 1978  29C,12B
# 1979  25G,27C

我尝试过的代码和我得到的输出

library(dplyr)
df %>% group_by(year) %>% distinct(year) %>% unite(bus, sep = ",", na.rm = F)

# A tibble: 2 x 1
# bus  
#  <chr>
#1 1978 
#2 1979 

代码中有什么错误,我怎样才能达到预期的输出?

4

1 回答 1

1

(评论后编辑)

一种可能的解决方案是

df %>% 
  group_by(year) %>% 
  summarise(bus = paste(bus, collapse = ",")) 

输出

# A tibble: 2 x 2
# Groups:   year [2]
#    year bus    
#   <dbl> <chr>  
# 1  1978 29C,12B
# 2  1979 25G,27C
于 2020-06-30T13:35:30.827 回答