1

I would like to count how many time points have each ID for example:

  ID Time
1 A 0
2 A 1
3 B 0
4 C 0
5 C 1
6 C 2
7 D 0

so I have Time 0 only: 2IDS that are: B and D Time 0 and 1 only: 1ID that is: A Time 1 only: none Time 0 and 2: none Time 0,1,2: 1ID that is: C

Thank you

Maël
  • 45,206
  • 3
  • 29
  • 67
Georg
  • 21
  • 2

1 Answers1

0

In base R, with two aggregates:

aggregate(Time ~ ID, data = df, FUN = \(x) toString(unique(x))) |>
  aggregate(ID ~ Time, data = _, FUN = unique)

     Time   ID
1       0 B, D
2    0, 1    A
3 0, 1, 2    C

Or with tapply:

tapply(df$Time, df$ID, toString) %>% 
  tapply(names(.), ., toString)

#      0    0, 1 0, 1, 2 
# "B, D"     "A"     "C" 

Or in dplyr:

df %>% 
  group_by(ID) %>% 
  summarise(Time = toString(Time)) %>% 
  group_by(Time) %>% 
  summarise(ID = toString(ID))

# A tibble: 3 × 2
  Time    ID   
  <chr>   <chr>
1 0       B, D 
2 0, 1    A    
3 0, 1, 2 C    
Maël
  • 45,206
  • 3
  • 29
  • 67
  • Thanks Mael! And if I want to count how many IDs I have in my 0; 0&1 etc using dplyr method how can I do this? – Georg Oct 03 '22 at 12:19
  • Check here: https://stackoverflow.com/questions/63062416/count-unique-combinations-of-variable-values-in-an-r-dataframe-column – Maël Oct 03 '22 at 13:00