I have a longitudinal dataset about individuals from different socioeconomic backgrounds. The raw data is broken up into high, middle, lower middle, and lower SES statuses. However, I want to add a fifth row that aggregates the lower middle and lower SES statuses. I know how to get the information that I need as columns (see below), but I'm not sure how to elegantly get that information into another row.
Here's a subset of my raw dataset:
library(dplyr)
test_data <- tibble(month = c(rep(c("Jan"), 4), rep(c("Feb"), 4)),
ses = c(rep(c("High", "Mid", "Mid Low", "Low"), 2)),
total = c(10, 20, 20, 30, 9, 11, 40, 60),
total_selected = c(9, 10, 8, 3, 8, 6, 8, 6)) %>%
group_by(month, ses) %>%
mutate(success_rate = total_selected/total)
And here's my code that does get the information that I need (i.e., it aggregates the information for lower and lower middle ses), but it puts them as columns instead of rows:
(test_data2 <- test_data %>%
group_by(month) %>%
mutate(three_ses_total = case_when(
ses %in% c("High", "Mid") ~ total,
ses %in% c("Mid Low", "Low") ~ (total[ses == "Mid Low"] + total[ses == "Low"])
),
three_ses_total_selected = case_when(
ses %in% c("High", "Mid") ~ total_selected,
ses %in% c("Mid Low", "Low") ~ (total_selected[ses == "Mid Low"] + total_selected[ses == "Low"])
),
three_ses_success_rate = case_when(
ses %in% c("High", "Mid") ~ success_rate,
ses %in% c("Mid Low", "Low") ~ three_ses_total_selected/three_ses_total
)))
Last, this is what I want the output to look like. Note: I want 5 rows--in other words, I still want the 4 raw classes in the dataset, but I also want the new combined lower middle and lower:
(answer <- tibble(month = c(rep(c("Jan"), 5), rep(c("Feb"), 5)),
ses = c(rep(c("High", "Mid", "Mid Low", "Low", "Mid Low and Low"), 2)),
total = c(10, 20, 20, 30, 50, 9, 11, 40, 60, 100),
total_selected = c(9, 10, 8, 3, 11, 8, 6, 8, 6, 14)) %>%
group_by(month, ses) %>%
mutate(success_rate = total_selected/total))
I'm open to any suggestion, but if there's a dplyr, tidyr, or other tidyverse function(s) that could help, I'd especially appreciate that. I was trying to think if tidyr's pivot functions would work, but I can't seem to crack it.