Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating Plots in a Loop (R)

I wrote this loop in R that generates a random data set and then makes a plot for this random data set:

    library(ggplot2)

results = list()

for (i in 1:100)

{

my_data_i = data.frame(var_1 = rnorm(100,10,10), var_2 = rnorm(100,10,10))

plot_i = ggplot(my_data_i, aes(x=var_1, y=var_2)) + geom_point() + ggtitle(paste0("graph", i))

results[[i]] = plot_i

}

Can someone please show me how to extract each individual plot from this list and create a file in the global environment : plot_1, plot_2… plot_100?

Thank you!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As we mentioned in the comments, it is better not to create 100 objects in the global env, instead store it in a list. This can be done either with a for loop (as showed in the OP’s code, but create a NULL list of required length and do the assign)

results <- vector('list', 100)
for (i in seq_along(results)

{

my_data_i <- data.frame(var_1 = rnorm(100,10,10), var_2 = rnorm(100,10,10))

plot_i <- ggplot(my_data_i, aes(x=var_1, y=var_2)) +
            geom_point() + 
             ggtitle(paste0("graph", i))

results[[i]] = plot_i

}
names(results) <- paste0('plot_', seq_along(results))

and then extract with either $ or [[

results[['plot_1']]
results$plot_1

Another option without preassigning is to use lapply

results2 <- lapply(1:100, function(i) {
          my_data_i <- data.frame(var_1 = rnorm(100,10,10), var_2 = rnorm(100,10,10))

 ggplot(my_data_i, aes(x=var_1, y=var_2)) +
            geom_point() + 
             ggtitle(paste0("graph", i))
   })
names(results2) <- paste0("plot_", seq_along(results2))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading