【问题标题】:Graphing using list of dataframes使用数据框列表绘制图表
【发布时间】:2021-11-24 19:22:35
【问题描述】:

跟进这篇帖子here

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

【问题讨论】:

    标签: r ggplot2 tidymodels


    【解决方案1】:

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

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

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

    请注意,这将返回 一个 绘图列表,可通过normal indexing 访问。

    【讨论】:

    • 很好的解决方案。谢谢!
    猜你喜欢
    • 2018-06-20
    • 2018-11-06
    • 2020-11-10
    • 2018-08-01
    • 2019-07-28
    • 1970-01-01
    • 2021-12-27
    • 2020-01-02
    • 2021-04-03
    相关资源
    最近更新 更多