创建一个函数,根据两个不同长度的输入变量将多个 ggplots 保存在命名文件夹中

Create a function to save multiple ggplots in named folders based on two input variables with different lengths

提问人:flâneur 提问时间:10/4/2023 更新时间:10/4/2023 访问量:41

问:

我有一个函数可以保存来自不同模型的多个 ggplot,如下所示:


library(tidyverse)
library(marginaleffects)

outcome_var_list = c("mpg","cyl","wt","hp")
interact_var_list =  c("gear","am","wt")

model_ <- function(k){
  
  outcome_var_list = outcome_var_list[outcome_var_list == k] 
  
  results = list()
  for (r in interact_var_list) {
    f = paste(k, "~", r, "*factor(vs)")
    m = lm(f, subset(mtcars, carb %in% c(1,2,3,4)))
    s = plot_slopes(m, variables = r, condition = "vs", draw = FALSE)
    tmp = s[, c("estimate", "conf.low", "conf.high", "vs")]
    tmp$outcome = k
    tmp$regressor = r
    results = c(results, list(tmp))
  }
  results = do.call("rbind", results)  
  
  
  plot1 = results %>% mutate(min = min(conf.low), max = max(conf.high)) %>% 
    ggplot(aes(x=factor(vs), y=estimate, color = regressor, ymin=conf.low, ymax=conf.high)) + 
    geom_errorbar(position = position_dodge(0.4)) + geom_point(position = position_dodge(0.4))
  
  ggsave(plot1,file=paste0("plot_",k,".png"),path="folder1/subfolder")
  
}

safe_model <- safely(model_)
iterate <- sapply(outcome_var_list,safe_model)


我现在想对数据的多个子集重复此操作。因此,我尝试将两个变量映射到函数(现在而不是 ),以获取子集的子集并在以子集变量命名的不同子文件夹中生成图。新代码如下所示:mapplysapplymtcars


outcome_var_list = c("mpg","cyl","wt","hp")
interact_var_list =  c("gear","am","wt")
subset_list = unique(mtcars$disp)

model_ <- function(k,c){
  
mtcars = mtcars[mtcars$disp == c,]
  
  
  outcome_var_list = outcome_var_list[outcome_var_list == k] 
  
  results = list()
  for (r in interact_var_list) {
    f = paste(k, "~", r, "*factor(vs)")
    m = lm(f, subset(mtcars, carb %in% c(1,2,3,4)))
    s = plot_slopes(m, variables = r, condition = "vs", draw = FALSE)
    tmp = s[, c("estimate", "conf.low", "conf.high", "vs")]
    tmp$outcome = k
    tmp$regressor = r
    results = c(results, list(tmp))
  }
  results = do.call("rbind", results)  
  
  
  plot1 = results %>% mutate(min = min(conf.low), max = max(conf.high)) %>% 
    ggplot(aes(x=factor(vs), y=estimate, color = regressor, ymin=conf.low, ymax=conf.high)) + 
    geom_errorbar(position = position_dodge(0.4)) + geom_point(position = position_dodge(0.4))
  
  ggsave(plot1,file=paste0("plot_",k,".png"),path = paste0("folder1/",c))
  
}

safe_model <- safely(model_)
iterate <- mapply(safe_model,outcome_var_list,subset_list)

不幸的是,我收到以下警告,并且没有生成任何绘图:warning: longer argument not a multiple of length of shorter

如何将函数映射到不同的子集并完全重复我对整个数据集所做的操作,而是使用子集并创建新的子文件夹?我知道我的输入变量具有不同的长度,但我希望生成每个组合。因此,对于每个 outcome_var_list 值,disp == 160 应该有 1 个图,disp == 108 应该有 1 个图,依此类推。mtcars

R 子集 sapply mapply ggsave

评论


答: 暂无答案