aimalik
aimalik

Reputation: 13

How to loop over variables in R?

I'm trying to automate the generation of several segmented bar plots. There are thirteen variables that I'm trying to loop over, named as per the following convention: mc_q#. I'm trying the following code, but all it does is generate a plot called px and then stop running:

for (x in 1:13) {
px <- ggplot(tct_tqi, 
             aes(x = mc_qx, 
                 fill = test_category)) + 
  geom_bar(position = "fill") +
  labs(fill="TCT mark band")
}

Will be grateful for any help!!

Upvotes: 0

Views: 353

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389315

You may create a list of plots -

library(ggplot2)

variables <- paste0('mc_q', 1:13)
result_px <- vector('list', length(variables))

for (i in seq_along(variables)) {
  result_px[[i]] <- ggplot(tct_tqi, 
            aes(x = .data[[variables[i]]], fill = test_category)) + 
    geom_bar(position = "fill") +
    labs(fill="TCT mark band")
}

result_px[[1]] would return the 1st plot, result_px[[2]] the 2nd plot and so on.

Upvotes: 2

Related Questions