user13933695
user13933695

Reputation: 41

Put dplyr & ggplot in Loop/Apply

I'm newish to R programming and am trying to standardise, or generalise, a piece of code so that I apply it to different data exports of the same structure. The code is trivial, but I am having trouble getting getting it to loop:

Here is my code:

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()
 

I want to generalise the code so that I can switch out 'Age' w/ variables I put into a list. Here is my amateur code:

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()
}

And this doesn't work. The datasets I will be receiving will have the same variables, just different observations and so standardising this process will be a lifesaver.

Thanks in advance.

Upvotes: 0

Views: 118

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

You were probably trying to do :

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())

This will return you list of plots which can be accessed as plot_list[[1]], plot_list[[2]] etc. Also look into facets to combine multiple plots.

Upvotes: 1

Related Questions