简体   繁体   中英

Nested loop in R to sequence over all combinations of parameters

I have the following three parameters:

a <- c("brown", "red", "purple", "yellow", "blue", "green")
b <- c("unknown", "medium", "low", "high")
c <- c("group1", "group2")

I want to loop through each combination of parameters in order to obtain a list of names of those very parameters. The result should look like the following:

$plot_group1_unknown_brown
[1] "plot_group1_unknown_brown"

$plot_group2_unknown_brown
[1] "plot_group2_unknown_brown"

$plot_group1_medium_brown
[1] "plot_group1_medium_brown"

$plot_group2_medium_brown
[1] "plot_group2_medium_brown"

$plot_group1_low_brown
[1] "plot_group1_low_brown"
.
.
.

Now I want achieve this using any of the apply family of functions or really any approach other than a for loop. I can accomplish this with a for loop like so:

for (x in a) { 
  for (a in b) { 
    for (i in c) { 

      plot_name <- paste( 'plot', i, a, x, sep = '_' )
      plot_list[[plot_name]] <- plot_name

    }
  }
}

I would also like to note that this is just an example. In my actual use case, plot_name (on the RHS) would be a function that takes the same parameters as the ones used inside the paste() function above it. Something along the lines of plot_list[[plot_name]] <- some_plotting_function(x, i, a) and the result would be a list of ggplot2 objects.

We can use expand.grid on the vector s and paste

v1 <- paste0('plot_', do.call(paste, c(expand.grid(c, b, a), sep="_")))
lst1 <- setNames(as.list(v1), v1)
head(lst1)
#$plot_group1_unknown_brown
#[1] "plot_group1_unknown_brown"

#$plot_group2_unknown_brown
#[1] "plot_group2_unknown_brown"

#$plot_group1_medium_brown
#[1] "plot_group1_medium_brown"

#$plot_group2_medium_brown
#[1] "plot_group2_medium_brown"

#$plot_group1_low_brown
#[1] "plot_group1_low_brown"

#$plot_group2_low_brown
#[1] "plot_group2_low_brown"

You could use expand.grid to get all possible combinations and then use apply row-wise to pass the parameters to the function.

complete_list <- expand.grid(c, b, a)
#Can also use cross_df from purrr
#complete_list <- purrr::cross_df(list(c = c, b = b, a = a))
apply(complete_list, 1, function(x) some_plotting_function(x[1], x[2], x[3]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM