在 R 中使用 assign 函数时,如何将图形对象存储到列表中?

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

我创建了以下函数,它接受一个数据框并输出多个图:

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)
}

如何在创建图形对象时将它们放入列表中,以便最终将它们传递给 grid.arrange函数? assign 函数将它们放在一个变量中,但如何让循环将其放入列表中?

不是使用 assign 在全局环境中创建对象,而是在顶部初始化一个 list 'myGlist',然后分配指向它的每次迭代的输出

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)
   }