r - 在一列中按类别和不同日期分组
问题描述
数据如下:
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 进行变异。
样本输出
解决方案
您可以使用 将所有唯一日期组合在一个单元格中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]
推荐阅读
- wordpress - 如何在 Wordpress 类别 rss 提要上显示特色图片?
- algorithm - 递归时间复杂度计算
- node.js - 在 nodejs 上使用加密为 jsonwebtoken 创建 RSA SHA256
- angular - Aspnetboilerplate Angular 文件上传
- c - 即使文件存在,访问(路径,标志)也返回 0
- c - 在 C 中使用 pthread 和并发的 Segfault
- elasticsearch - 从数组内容中进行 Elasticsearch 搜索
- java - 声明新的 lunchBag 对象时出现“错误:找不到符号”?
- javascript - 是否有可能通过仅使用 CSS 和 HTML 将鼠标悬停来制作一个将消失的组件?
- java - 将对象与 JSON 相互转换