首页 > 解决方案 > 在一列中按类别和不同日期分组

问题描述

数据如下:

a <- c('2020-01-01','2020-01-03','2020-01-05','2020-05-01','2020-06-01')
b <- c('X1','X1','X1','X2','X2')
df <- data.frame(a,b)

按列 'b' 分组,并使用 col'a' 的所有不同值对 new_col 进行变异。

样本输出

在此处输入图像描述

标签: r

解决方案


您可以使用 将所有唯一日期组合在一个单元格中toString,并使用添加不同日期的计数n_distinct

library(dplyr)

df %>%
  group_by(b) %>%
  summarise(distinct_dates = toString(unique(a)), 
            distinct_count = n_distinct(a)) -> result
result

#   b     distinct_dates                     distinct_count
#  <chr> <chr>                                       <int>
#1 X1    2020-01-01, 2020-01-03, 2020-01-05              3
#2 X2    2020-05-01, 2020-06-01                          2

data.table可以这样做:

library(data.table)
setDT(df)[, .(distinct_dates = toString(unique(a)), 
              distinct_count = uniqueN(a)), b]

推荐阅读