在一系列参数上迭代或映射自定义函数

问题描述 投票:0回答:0

我有一些分析代码,可以在具有不同设置的多个数据块上重复使用。我已经模块化了这个过程,这样我就可以通过定义一些变量来指定要分析的设置和数据,然后调用分析代码,就像这样:

## Specify settings
input_var <- "foo"  # these are string parameters fed into various custom functions in the analysis code
dep_var <- "bar"
other_var <- "baz"
some_setting <- "Ni"
label <- "peng"
target_data <- list(neewom)   # this is a data tibble

## Call analysis code
## These include references to the settings variables specified above
source("first_analysis.R")
source("additional_analyses.R")
source("process_outputs.R")

随着模块化的进行,为了测试对各种数据和设置配置的分析,这工作得很好。

但是,我希望能够一次对许多不同的数据和设置组合运行此工作流程,而无需每次都重复代码。

我的做法是把所有的设置规范放在一个小标题中,设置变量作为列名,例如

# A tibble: 1 × 6
  input_var dep_var other_var some_setting label target_data     
  <chr>     <chr>   <chr>     <chr>        <chr> <list>          
1 foo       bar     baz       Ni           peng  <tibble [5 × 2]>

## Additional rows as needed to contain other configurations of settings

我觉得我必须有办法使用

map
apply
或类似的东西,然后在每一行上运行分析代码,如有必要,将分析代码包装在一个函数中,例如

run_analysis <- function(input_var, dep_var, other_var, some_setting, label, target_data) {
    source("first_analysis.R")
    source("additional_analyses.R")
    source("process_outputs.R")
}

但是我不知道该怎么做。首先是因为

map
(或
map2
)分别只允许一个(或两个)参数,而我的参数不止于此;其次,因为我不确定是否需要将每列中的特定变量分配给它们各自的名称作为中间步骤(或如何做到这一点)。我可以通过一次循环一行来做到这一点,但是有没有矢量化的方法来做到这一点?

r tidyverse apply purrr
© www.soinside.com 2019 - 2024. All rights reserved.