在 R 中的组之间创建源、目标和计数总和

Create Source, Target and sum of counts between a group in R

我有一个如下所示的数据框:

id product date
1 A month 0
1 A month 1
1 B month 2
2 A month 0
2 A month 1
2 A month 2
2 D month 3

期望的输出

source target product sum
month 0 month 1 A 2
month 0 month 1 B 0
month 1 month 2 A 1
month 1 month 2 B 1
month 2 month 3 D 1

目标是计算每个月的 ID 总数并按产品分组。
我只是完全坚持如何首先将列日期拆分为源和目标。也许一旦我这样做了,我就可以做类似的事情:

df %>% group(product,source,target) %>% mutate(length(unique(id))

不太确定,任何帮助都会很好。

这是一个尝试:不是预期的输出,因为正如@Jon Spring 指出的那样,它并不完全清楚:

library(dplyr)
library(readr) # parse_number
df %>% 
  mutate(date = parse_number(date)) %>% 
  group_by(id, product) %>% 
  add_count(name="sum") %>% 
  mutate(x = ifelse(sum>1, lead(date), date-1)) %>% 
  drop_na() %>% 
  mutate(source = ifelse(date < x, date, x), 
         target = ifelse(date > x, date, x), .keep="unused") %>% 
  mutate(across(c(source, target), ~paste("month", .)))
     id product   sum source  target 
  <int> <chr>   <int> <chr>   <chr>  
1     1 A           2 month 0 month 1
2     1 B           1 month 1 month 2
3     2 A           3 month 0 month 1
4     2 A           3 month 1 month 2
5     2 D           1 month 2 month 3