I am trying to perform a loop which loops through a list of single or multiple variables then sums a column. I am essentially trying to paste in from a list into the group_by() function so that it recognises the columns.
i.e. I want a list of grouping var/s like this, which I can amend depending on which variables or combinations I want to group by to aggregate another column
grp_by_list <- list("phase","phase,region","region")
which I can then use in a function like this:
grp_tabs <- list()
for(i in 1:length(grp_by_list)){
grp_tabs[[paste0(grp_by_list[[i]])]] <- table %>%
group_by(paste(grp_by_list[[i]]))%>%
summarise(total = sum(total),
n = n())}
It's the group_by() and pasting I am having a problem with, it works for the single variables but it doesn't like where I have two variables separated by a comma. However if I just type in the two variables separated by a comma (as shown below), that works fine. Does anyone know how to achieve this please?
Rather than getting an error, I am just getting output tables that all look identical where no grouping has taken place, it just gives me the sum and n for all data.
Some dummy data:
dummy_data <- tibble(phase=c("first","second","third","second","third","first","third","second","first","first"), region=c("south","east","west","north","south","east","south","west","north","west"),
total=c(12,33,45,63,45,67,10,20,29,56))