R specific combinations of number variables to calculate continuation rate

Viewed 57

The code I have so far:

continuation <- data %>%
  filter(TYPE == "group") %>%
  select(ID, YEAR, COURSE_YEAR) %>%
  group_by(ID) %>%
  distinct(COURSE_YEAR) %>%
  summarise(number = n())

Some sample data:

ID YEAR COURSE_YEAR
123545 2019 1
123545 2020 2
123654 2019 1
119236 2019 2
116787 2019 3
113435 2019 2
113435 2020 3

So I would want results something like

Year Course Years No.
2019 1 1
2019 1, 2 1
2019 2 1
2019 3 1
2019 2, 3 1

Course year has a range of values between 1 and 4. The distinct is needed as people may have multiple entries in the type column for each course year due to the nature of the underlying data.

I am trying to work out, for each of the years in the data set, how many ID numbers appear for the first time, and what combinations of course year there are. So I would expect most of the people appearing for the first time to have a course year of 1, but I'm interested in whether they are appearing in the data set for later years having progressed to the next year, or whether they are appearing for the first time with a course year != 1.

1 Answers

It's not entirely clear from the description, but I think this may be helpful.

For each ID, you can create a new column COURSE_YEARS that would contain a character value of all COURSE_YEAR values for that ID separated by a comma. unique is included since it was mentioned you needed distinct based on group.

A filter is added, so results will only include the first YEAR for a given ID.

Then, you can group_by both YEAR and COURSE_YEARS and summarise to get the number n of each of these combinations.

library(tidyverse)

data %>%
  group_by(ID) %>%
  mutate(COURSE_YEARS = toString(unique(COURSE_YEAR))) %>%
  filter(YEAR == first(YEAR)) %>%
  group_by(YEAR, COURSE_YEARS) %>%
  summarise(n = n())

Output

   YEAR COURSE_YEARS     n
  <int> <chr>        <int>
1  2019 1                1
2  2019 1, 2             1
3  2019 2                1
4  2019 2, 3             1
5  2019 3                1
Related