Working in R, I have a dataframe df that shows the number of students enrolled in each grade.
df <- structure(list(Grade = c("PK3", "PK4", "KG", "Grade 1", "Grade 2",
"Grade 3", "Grade 4", "Grade 5", "Grade 6", "Grade 7", "Grade 8",
"Grade 9", "Grade 10", "Grade 11", "Grade 12", "Ungraded"), Enrolled = c(4967,
6481, 7378, 7041, 6760, 6590, 6473, 6191, 5790, 5693, 5614, 7254,
4951, 4250, 3792, 238)), row.names = c(NA, -16L), class = c("tbl_df",
"tbl", "data.frame"))
I want to append two rows at the end: one which shows total enrollment in grades K-12 and the other which shows total enrollment for grades PK-12. I wrote code to do this using the {janitor} package, but this code seems unnecessarily long and complicated. Is there a better way to tell the code to append one row that sums up rows 3 to 16, and another row that sums up rows 1 to 16?
df2 = df %>% filter(Grade != "PK3" & Grade != "PK4") %>%
adorn_totals(where="row", name="k_12_total") %>%
filter(Grade == "k_12_total")
df = rbind(df, df2)
df2 = df %>% filter(Grade != "k_12_total") %>%
adorn_totals(where="row", name="pk_12_total") %>%
filter(Grade == "pk_12_total")
df = rbind(df, df2)
What if we simply just append two 1-row dataframes with the sums you want. Assuming you already know the indices its as easy as:
For multiple years use
colSums: