首页 > 解决方案 > 将 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()
}

这是行不通的。我将收到的数据集将具有相同的变量,只是不同的观察结果,因此标准化此过程将是救命稻草。

提前致谢。

标签: rggplot2dplyr

解决方案


您可能正在尝试这样做:

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]]等等。还可以查看构面以组合多个图。


推荐阅读