rgrob

In R while using assign function, how can I store graphic objects to a list?


I have created the following function which takes a data frame and outputs multiple plots:

boxplot_depend_vs_independ <- function(df_train) {
  
  train_int_names <- df_train %>% select_if(is.numeric)
  
  int_names <- names(train_int_names)
  
   for (i in int_names) {       
     
    assign(paste0("var_",i), 
           ggplot(train, aes_string(x = train$target, y = i)) + 
            geom_boxplot(color = 'steelblue', outlier.color = 'firebrick', 
                         outlier.alpha = 0.35) +
            labs(title = paste0(i,' vs target'), y = i, x= 'target') +
            theme_minimal() + 
            theme(
              plot.title = element_text(hjust = 0.45),
              panel.grid.major.y =  element_line(color = "grey", 
                                                 linetype = "dashed"),
              panel.grid.major.x = element_blank(),
              panel.grid.minor.y = element_blank(),
              panel.grid.minor.x = element_blank(),
              axis.ticks.x = element_line(color = "grey")
            )
           )
   }
  

  myGlist <- list(var_YOJ) # Example of one grob in a list

  gridExtra::grid.arrange(grobs = myGlist, nrow=4)
}

How do I put the graphic objects in a list as I create them so I can pass them in the end to the grid.arrange function? The assign function puts them in a variable, but how do I get the loop to put it inside a list?


Solution

  • Instead of creating objects in the global env with assign, initialize a list 'myGlist' at the top and then assign the output from each iteration directed towards it

    boxplot_depend_vs_independ <- function(df_train) {
    
      train_int_names <- df_train %>% 
                select_if(is.numeric)
    
      int_names <- names(train_int_names)
       myGlist <- vector('list', length(int_names))
       names(myGlist) <- int_names
      for (i in int_names) {       
     
       myGlist[[i]] <- 
           ggplot(train, aes_string(x = train$target, y = i)) + 
            geom_boxplot(color = 'steelblue', outlier.color = 'firebrick', 
                         outlier.alpha = 0.35) +
            labs(title = paste0(i,' vs target'), y = i, x= 'target') +
            theme_minimal() + 
            theme(
              plot.title = element_text(hjust = 0.45),
              panel.grid.major.y =  element_line(color = "grey", 
                                                 linetype = "dashed"),
              panel.grid.major.x = element_blank(),
              panel.grid.minor.y = element_blank(),
              panel.grid.minor.x = element_blank(),
              axis.ticks.x = element_line(color = "grey")
            )
           
          }
    
    
    
    
        gridExtra::grid.arrange(grobs = myGlist, nrow=4)
       }