有没有一种通过计算类别数将长转换为宽的整洁方法?

Is there a tidy way to convert long to wide by counting the number of category?

> dd <- data.frame(id=c("a","b","b","c","c","c"),names=1:6)
> target <- data.frame(id=c("a","b","c"),names = c("1","2,3","4,5,6"),counts=c(1,2,3))
> dd
  id names
1  a     1
2  b     2
3  b     3
4  c     4
5  c     5
6  c     6
> target
  id names counts
1  a     1      1
2  b   2,3      2
3  c 4,5,6      3

如何将 dd 转换为 target;最好的解决方案可能是使用 pivotal_wider;但我不知道该怎么做。

只需按 id 分组并汇总,即

library(dplyr)

dd %>% 
 group_by(id) %>% 
 summarise(names = toString(names), 
           counts = n())