I have a function to save multiple ggplots from different models such as the following:
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)
I now want to repeat this for multiple subsets of the data. I therefore attempt to map two variables to the function (now mapply instead of sapply) to take subsets of mtcars and produce plots in different subfolders named for the subset variable. The new code looks like the following:
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)
Unfortunately, I receive the following warning, and no plots are generated: warning: longer argument not a multiple of length of shorter
How can I map the function to different subsets and repeat exactly what I did for the entire mtcars dataset, but instead with subsets and creating new subfolders? I know that my input variables have different lengths, but I want every combination to be generated. So for each value of outcome_var_list, there should be 1 plot for disp == 160, 1 for disp == 108, etc.