1

I want to count the total number of dates each person have (from dataset 1 to dataset2). For example, ID 1 has 3 unique dates so total_num_dates would be 3, ID 2 has 1 unique date so total_num_dates would be 1, etc. Is there a way to do this?

I appreciate all the help there is! Thanks!

dataset 1:

ID <- c(1,1,1,2,2,3,3)
Date <-as.Date(c("2021/08/04","2021/08/05","2021/08/06",
                 "2021/08/04","2021/08/04",
                 "2021/08/04","2021/08/05"))
x <- data.frame(ID,Date)

ID      Date
1       2021/08/04
1       2021/08/05
1       2021/08/06
2       2021/08/04
2       2021/08/04
3       2021/08/04
3       2021/08/05

dataset 2 (desired)

ID <- c(1,1,1,2,2,3,3)
Date <-as.Date(c("2021/08/04","2021/08/05","2021/08/06",
                 "2021/08/04","2021/08/04",
                 "2021/08/04","2021/08/05"))
total_num_dates <- c(3,3,3,1,1,2,2)
x <- data.frame(ID,Date,total_num_dates)

ID      Date             total_num_dates
1       2021/08/04       3
1       2021/08/05       3
1       2021/08/06       3
2       2021/08/04       1
2       2021/08/04       1
3       2021/08/04       2
3       2021/08/05       2
Bruh
  • 277
  • 1
  • 6

1 Answers1

1

Code

library(dplyr)

x %>% 
  group_by(ID) %>% 
  mutate(n = n_distinct(Date))

Output

# A tibble: 7 x 3
# Groups:   ID [3]
     ID Date           n
  <dbl> <date>     <int>
1     1 2021-08-04     3
2     1 2021-08-05     3
3     1 2021-08-06     3
4     2 2021-08-04     1
5     2 2021-08-04     1
6     3 2021-08-04     2
7     3 2021-08-05     2
Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32