使用数据框列表绘图

Graphing using list of dataframes

跟进此事 post

我使用 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"))

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

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

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

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

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

lapply(pred1, my_plot_function)

请注意,这将 return 地块列表 ,可供 normal indexing 访问。