首页 > 解决方案 > 将不同数量的输入作为 r 中的列表传递给函数(应用程序:plot_summs)

问题描述

我正在尝试使用 plot_summs 以统一的样式制作大量绘图。我想要一个作为包装器的函数,并且可以将绘图作为循环的一部分生成。但是,包含的模型数量各不相同,我无法弄清楚如何将不同数量的模型传递给 plot_summs。

使用 plot_summs 文档中的示例,修改以说明我的问题:

states <- as.data.frame(state.x77)
fit1 <- lm(Income ~ Frost + Illiteracy + Murder +
             Population + Area + `Life Exp` + `HS Grad`,
           data = states, weights = runif(50, 0.1, 3))
fit2 <- lm(Income ~ Frost + Illiteracy + Murder +
             Population + Area + `Life Exp` + `HS Grad`,
           data = states, weights = runif(50, 0.1, 3))
fit3 <- lm(Income ~ Frost + Illiteracy + Murder +
             Population + Area + `Life Exp` + `HS Grad`,
           data = states, weights = runif(50, 0.1, 3))

# I can pass a varying number of models to plot_summs, and it will work fine:
plot_summs(fit1, fit2, fit3,
           coefs = c("Frost Days" = "Frost", "% Illiterate" = "Illiteracy",
                     "Murder Rate" = "Murder"),
           scale = TRUE, robust = TRUE)
plot_summs(fit1, fit2,
           coefs = c("Frost Days" = "Frost", "% Illiterate" = "Illiteracy",
                     "Murder Rate" = "Murder"),
           scale = TRUE, robust = TRUE)

# However, in order to have a wrapper function that can flexibly plot a varying
# number of models, I have the models stored as a list:
variablenumberinputs <- list(fit1,fit2)

# I can plot from this list as long as I know the number of items in it:
plot_summs(variablenumberinputs[[1]],variablenumberinputs[[2]],recursive = FALSE),
           coefs = c("Frost Days" = "Frost", "% Illiterate" = "Illiteracy",
                     "Murder Rate" = "Murder"),
           scale = TRUE, robust = TRUE)

# But I cannot figure out a version of "unlist" or similar that will let me 
# do this without hard-coding the number of models. Eg, the following fails:
plot_summs(unlist(variablenumberinputs,recursive = FALSE),
           coefs = c("Frost Days" = "Frost", "% Illiterate" = "Illiteracy",
                     "Murder Rate" = "Murder"),
           scale = TRUE, robust = TRUE)

# note that just passing the list to the function results in a plot, but the plot is incorrect.

标签: rlist

解决方案


我们可以用do.call

do.call(plot_summs, c(variablenumberinputs, 
            list(coefs = c("Frost Days" = "Frost",
               "% Illiterate" = "Illiteracy",
                 "Murder Rate" = "Murder"),
       scale = TRUE, robust = TRUE)))

-输出

在此处输入图像描述


推荐阅读