Looking to generate a new column with a count of each 'class' occurrence per year and per term.
The dput for the df is as follows:
structure(list(class = c("ART", "ART", "ART", "ART", "ART", "PE",
"PE", "PE", "PE", "PE", "Science", "Science", "Science", "Science",
"Science", "Music", "Music", "Music", "Music", "Music", "Music",
"Music", "Music", "Music", "Music", "Music", "Music", "Music",
"PE", "PE", "PE", "PE", "PE", "PE", "PE", "PE", "PE", "ART",
"ART", "ART"), year = c("2019", "2020", "2019", "2020", "2019",
"2020", "2019", "2020", "2019", "2020", "2019", "2020", "2019",
"2020", "2019", "2020", "2019", "2020", "2019", "2020", "2019",
"2020", "2019", "2020", "2019", "2020", "2019", "2020", "2019",
"2020", "2019", "2020", "2019", "2020", "2019", "2020", "2019",
"2020", "2019", "2020"), term = c("Semester 1", "Semester 1",
"Semester 1", "Semester 1", "Semester 1", "Semester 1", "Semester 1",
"Semester 1", "Semester 1", "Semester 1", "Semester 1", "Semester 1",
"Semester 1", "Semester 1", "Semester 1", "Semester 1", "Semester 1",
"Semester 1", "Semester 1", "Semester 1", "Semester 2", "Semester 2",
"Semester 2", "Semester 2", "Semester 2", "Semester 2", "Semester 2",
"Semester 2", "Semester 2", "Semester 2", "Semester 2", "Semester 2",
"Semester 2", "Semester 2", "Semester 2", "Semester 2", "Semester 2",
"Semester 2", "Semester 2", "Semester 2")), class = "data.frame", row.names = c(NA,
-40L))
Happy to hard code each year/term as per below, but can't hardcode each class as in my real dataset there are 1000+ classes. My attempt was as follows:
df$enrols[df$year==2020 & df$term=="Semester 1"] = length(unique(df$class))
Asked this question yesterday and received some helpful answers but don't produce the required output. The question was subsequentlyt closed hence the new question.
What I'm after is a count for how many times each class appears for a certain term and year. For example, in the df provided, Observations with 'Art' in 'Semester 1' and '2019' should have a column ('enrols') with '4' as there are 4 occurences for 'Art' in that year and term.