【问题标题】:Nested loop in R to sequence over all combinations of parametersR中的嵌套循环对所有参数组合进行排序
【发布时间】:2020-03-28 01:11:05
【问题描述】:

我有以下三个参数:

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

我想遍历每个参数组合,以获得这些参数的名称列表。结果应如下所示:

$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"
.
.
.

现在我想使用任何 apply 系列函数或除 for 循环之外的任何方法来实现此目的。我可以使用这样的 for 循环来完成此操作:

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

    }
  }
}

我还想指出,这只是一个示例。在我的实际用例中,plot_name(在 RHS 上)将是一个函数,它采用与上面 paste() 函数内部使用的参数相同的参数。类似于plot_list[[plot_name]] &lt;- some_plotting_function(x, i, a) 的内容,结果将是 ggplot2 对象的列表。

【问题讨论】:

    标签: r loops lapply


    【解决方案1】:

    我们可以在vectors 和paste 上使用expand.grid

    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"
    

    【讨论】:

    • plot_name(在 RHS 上)将是一个函数,其参数与上面的 paste() 函数中使用的参数相同。类似于 plot_list[[plot_name]]
    【解决方案2】:

    您可以使用expand.grid 获取所有可能的组合,然后使用apply 逐行将参数传递给函数。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-28
      • 1970-01-01
      • 1970-01-01
      • 2020-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多