r - 使用数据框列表绘制图表
问题描述
在此处跟进此帖子
我使用 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)
解决方案
遵循与上一个问题相同的模式 - 使用lapply
。
这通过定义一个函数来执行绘图变得更容易。
my_plot_function <- function(x) {
ggplot(data = x) +
geom_point(aes(x=year, y=value))+
facet_wrap(~ group)
}
lapply(pred1, my_plot_function)
请注意,这将返回一个绘图列表,可通过正常索引访问。
推荐阅读
- swift - 如何使 UICollectionView 单元格可触摸/可点击?
- java - 如何在活动中打开 BottomNavigationView 菜单项
- bash - 用于删除断字字符的 Sed 脚本
- sql - 提高 Hive 中 Ntile 函数的速度
- node.js - Discord.js 反应收集器不听收集器.on('collect')
- javascript - 将 JSON XMLHttpRequest 的分页部分呈现为 HTML
- java - Heroku 未部署
- c - 编译后删除的可执行文件
- python - Python Flask:返回 MCQ 输出,突出显示正确和选择的答案
- flutter - Flutter:如何使用 ListView.builder 在聊天 UI 中从上到下显示信息