首页 > 解决方案 > 使用数据框列表绘制图表

问题描述

在此处跟进此帖子

我使用 tidymodels 将回归拟合到数据框的分组列表中。然后我将值预测到另一个数据框列表中。

# Code from the original question
library(dplyr)

year <- rep(2014:2018, length.out=10000)
group <- sample(c(0,1,2,3,4,5,6), replace=TRUE, size=10000)
value <- sample(10000, replace=T)
female <- sample(c(0,1), replace=TRUE, size=10000)
smoker <- sample(c(0,1), replace=TRUE, size=10000)
dta <- data.frame(year=year, group=group, value=value, female=female, smoker=smoker)

# cut the dataset into list
table_list <- dta %>%
  group_by(year, group) %>%
  group_split()

# fit model per subgroup
model_list <- lapply(table_list, function(x) glm(smoker ~ female, data=x,
                                                 family=binomial(link="probit")))

# create new dataset where female =1
dat_new <- data.frame(dta[, c("smoker", "year", "group")], female=1) 

# predict
pred1 <- lapply(model_list, function(x) predict.glm(x, type = "response"))

现在,我想使用该预测变量列表来绘制使用ggplot和的组facet_wrap。这最后一步是我迷路的地方。如何使用数据框列表绘制图表?这不运行。

ggplot(pred1)+
  geom_point(aes(x=year, y=value))+
  facet_wrap(~ group)

标签: rggplot2tidymodels

解决方案


遵循与上一个问题相同的模式 - 使用lapply

这通过定义一个函数来执行绘图变得更容易。

my_plot_function <- function(x) {
  ggplot(data = x) +
    geom_point(aes(x=year, y=value))+
    facet_wrap(~ group)
}

lapply(pred1, my_plot_function)

请注意,这将返回一个绘图列表,可通过正常索引访问。


推荐阅读