r 计算时间的组合

r counting the combination of time

这更难编码,更难解释。如果我的解释令人困惑,我深表歉意,我会尝试以这种方式解释数据。

我有一个包含 3 列的数据集

ID        Vaccine        Time
 1         A              Winter
 1         B              Spring
 
 2         A              Spring
 2         B              Winter
 2         B              Fall
 
 3         C              Fall
 3         A              Fall
 3         B              Fall

 4         A              Winter
 4         A              Spring

 5         A              Winter

如您所见,有


Vaccine      Winter.Only     Spring.Only       Fall.Only     Winter.Spring     Winter.Fall    Spring.Fall
A            2               1                 1             1 

Vaccine      Winter.Only     Spring.Only       Fall.Only     Winter.Spring     Winter.Fall    Spring.Fall
B                            1                 1                               1 

Vaccine      Winter.Only     Spring.Only       Fall.Only     Winter.Spring     Winter.Fall    Spring.Fall
C                                              1                                

最终的数据集应该是这样的

Vaccine      Winter.Only     Spring.Only       Fall.Only     Winter.Spring     Winter.Fall    Spring.Fall
A            2               1                 1             1 
B                            1                 1                               1 
C                                              1

主要是我试图为每种疫苗(行)创建一个数据集,有多少患者只接种了一种疫苗以及何时(冬季,Spring,秋季)以及有多少患者接种了两种或三种疫苗相同类型且当 (Winter.Spring or Winter.Fall or Spring. Fall or Winter.Spring.Fall)

非常感谢任何有关如何执行此操作的想法或建议。

library(dplyr); library(tidyr)
df %>% 
  arrange(Time) %>%
  group_by(ID, Vaccine) %>%
  summarize(Times = paste(Time, collapse = "_and_"), .groups = "drop") %>%
  count(Vaccine, Times) %>%
  pivot_wider(names_from = Times, values_from = n)

结果

# A tibble: 3 x 6
  Vaccine  Fall Spring Spring_and_Winter Winter Fall_and_Winter
  <chr>   <int>  <int>             <int>  <int>           <int>
1 A           1      1                 1      2              NA
2 B           1      1                NA     NA               1
3 C           1     NA                NA     NA              NA