I have a df similar to the following:
df <- data.frame("name" = c("sue","joe","tom"),
"x0_date" = c("2020-1-20", "2020-2-20", "2020-3-20"),
"x0_class" = c("biology", "physics", "chemistry"),
"x1_date" = c("2021-4-18", NA, "2021-6-18"),
"x1_class" = c("english", NA, "drama"))
df
name x0_date x0_class x1_date x1_class
1 sue 2020-1-20 biology 2021-4-18 english
2 joe 2020-2-20 physics <NA> <NA>
3 tom 2020-3-20 chemistry 2021-6-18 drama
I am trying to pivot longer such that my outcome is as follows:
name date class
1 sue 2020-1-20 biology
2 sue 2021-4-18 english
3 joe 2020-2-20 physics
4 tom 2020-3-20 chemistry
5 tom 2021-6-18 drama
I guess I've only ever pivoted when some of the data is numeric, so I'm having trouble. I've tried something like:
test <- df %>%
pivot_longer(matches("date|class"),
names_to = c("date", "class"),
names_pattern = "(\\d+)_(.+)",
values_drop_na = TRUE)
But the output isn't quite right. If it's relevant, my wide data is extremely wide ("x0" to "x_400"). Any help is appreciated!