1

This is my first question here!

I need to change the column names of several dfs in a list through a loop but do not really know how to do it.

CONTEXT: I have a df with 14 variables: 13 themes (qualitative) + Area. I need to produce a summary table for each theme (Theme vs Area) and since they are many to do individually using dplyr, I summarized them through a loop. This resulted in a list of 13 dfs, to which I was able to split them into individual dfs and print a gt table for each one (please see coding below).

However, (I guess) since I looped through columns and they all have levels, the column name in the df is < fct > and I would like it to be Theme + Number (E.g. Theme1,Theme2,Theme#) instead. Can someone help, please?

This is what I was able to do so far:

themes = c("Theme1","Theme2","Theme3","Theme4","Theme5","Theme6",
         "Theme7","Theme8","Theme9","Theme10","Theme11","Theme12","Theme13")
list <- list()
t = 1

Produce list of summary DFs

for (i in themes) {
  list[[t]] = data%>% 
    group_by({{i}}) %>% 
    summarise_at(vars(WK_AREA), sum)%>%
    mutate_if(is.numeric, round, 2)
  t = t + 1
}

Split list into individual DFs and print table

for (i in seq_along(list)) {
  assign(paste0("Theme", i), value = list[[i]])
  print(gt(list[[i]]))
}  

The results are like the picture below:

enter image description here

lovalery
  • 4,524
  • 3
  • 14
  • 28

1 Answers1

0

We may need to either use i within across as it is a string or convert to symbol and evaluate (!!) i.e. group_by(!! sym(i))

lst1 <- vector('list', length(themes))
names(lst1) <- themes
for (i in themes) {
  lst1[[i]] = data%>% 
    group_by(across(all_of(i))) %>% 
    summarise(across(WK_AREA, sum))%>%
    mutate(across(where(is.numeric), round, 2))
  
}
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Hi Akrun, thank you so much for your help. The code worked perfectly! Thanks for the explanation on the group_by parameters - this will be very useful in my future work. Best regards, Lari. – Lari Delazari Mar 31 '22 at 09:52