假设我有:
Date ID
2000-01-01 1
2000-01-02 1
2000-01-03 1
2000-01-01 2
2000-01-01 2
2000-01-01 3
2000-01-10 3
2000-01-04 3
我想按 ID 计算连续日期。我怎样才能得到类似的东西:
Date ID count
2000-01-01 1 1
2000-01-02 1 2
2000-01-03 1 3
2000-01-01 2 1
2000-01-01 2 1
2000-01-01 3 1
2000-01-10 3 3
2000-01-04 3 2
最佳答案
我们可以在按“ID”分组后对“日期”的排序
唯一
值使用match
library(dplyr)
df1 %>%
group_by(ID) %>%
mutate(count = match(Date, sort(unique(Date)))) %>%
ungroup
-输出
# A tibble: 8 × 3
Date ID count
<date> <int> <int>
1 2000-01-01 1 1
2 2000-01-02 1 2
3 2000-01-03 1 3
4 2000-01-01 2 1
5 2000-01-01 2 1
6 2000-01-01 3 1
7 2000-01-10 3 3
8 2000-01-04 3 2
或者另一个选项是dense_rank
df1 %>%
group_by(ID) %>%
mutate(count = dense_rank(Date)) %>%
ungroup
数据
df1 <- structure(list(Date = structure(c(10957, 10958, 10959, 10957,
10957, 10957, 10966, 10960), class = "Date"), ID = c(1L, 1L,
1L, 2L, 2L, 3L, 3L, 3L)), row.names = c(NA, -8L), class = "data.frame")
关于r - 有没有办法计算 R dplyr 中的唯一日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71365997/