Home > Back-end >  Creating Plots in a Loop (R)
Creating Plots in a Loop (R)

Time:10-17

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!

CodePudding user response:

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

CodePudding user response:

I think I just figured this out?

list2env(setNames(results,paste0("plot",seq(results))),envir = .GlobalEnv)

Is this correct?

  • Related