r - 将 dplyr & ggplot 放入 Loop/Apply
问题描述
我对 R 编程很陌生,并且正在尝试标准化或概括一段代码,以便我将其应用于相同结构的不同数据导出。代码很简单,但我无法让它循环:
这是我的代码:
plot <- data %>%
group_by(Age, ID) %>%
summarise(Rev = sum(TotalRevenue)) %>%
ggplot(aes(
x = AgeGroup,
y = Rev,
fill = AgeGroup
)) +
geom_col(alpha = 0.9) +
theme_minimal()
我想概括代码,以便我可以用我放入列表的变量来切换“年龄”。这是我的业余代码:
cols <- c(data$Col1, data$Col2) #Im pretty sure this is wrong
for (i in cols) {
plot <- data %>%
group_by(i, ID) %>%
summarise(Rev = sum(TotalRevenue)) %>%
ggplot(aes(
x = AgeGroup,
y = Rev,
fill = AgeGroup
)) +
geom_col(alpha = 0.9) +
theme_minimal()
}
这是行不通的。我将收到的数据集将具有相同的变量,只是不同的观察结果,因此标准化此过程将是救命稻草。
提前致谢。
解决方案
您可能正在尝试这样做:
library(dplyr)
library(rlang)
cols <- c('col1', 'col2')
plot_list <- lapply(cols, function(i)
data %>%
group_by(!!sym(i), ID) %>%
summarise(Rev = sum(TotalRevenue)) %>%
ggplot(aes(x = AgeGroup,y = Rev,fill = AgeGroup)) +
geom_col(alpha = 0.9) + theme_minimal())
这将返回您可以访问的图列表plot_list[[1]]
,plot_list[[2]]
等等。还可以查看构面以组合多个图。
推荐阅读
- android-studio - Android Studio SDK 30 (2021) webview 如何使文件输入提示用户画廊、照片或视频并实际上传
- d3.js - 在 D3 sankey 图中更改节点颜色
- java - Java - 地图
> 遍历列表并跳过前 N 个条目 - pos-tagger - POS/NER 能够区分在多个上下文中使用的同一个词吗?
- php - 如何反序列化,然后将生成的多维数组转换为纯文本,去掉代码?
- azure - 将 Azure Sql 数据库限制为只能从不同区域的某些 Azure 应用服务访问
- python - 如何在 Pandas 中更改 MultiIndex 数据框列中某些行的值
- python - 使用 PySimpleGUI 时如何启用并响应最大化按钮
- vue.js - Vuetify:尽管 v-model 变量设置为 false,但 v-dialog 不会关闭
- c++ - 错误 LNK2005 DllMain 已在 uafxcw.lib(dllmodul.obj) 中定义