首页 > 解决方案 > R如何将可选参数的NULL传递给函数(例如在for循环中)

问题描述

我编写了一个 for 循环来测试 R 中排序函数的不同设置(包“vegan”,由“phyloseq”调用)。我在一个列表 ( sample_subset_list) 中有几个数据子集,因此,为所有这些子集测试不同的参数会产生许多组合。

排序函数包含可选参数formula,我想在有和没有公式的情况下执行我的排序。我认为NULL不使用formula参数的正确方法是什么?NULL但是在使用 for 循环(或应用等)时如何通过?

使用 phyloseq 示例数据:

library(phyloseq)
data(GlobalPatterns)
ps <- GlobalPatterns
ps1 <- filter_taxa(ps, function (x) {sum(x > 0) > 10}, prune = TRUE)
ps2 <- filter_taxa(ps, function (x) {sum(x > 0) > 20}, prune = TRUE)
sample_subset_list <- list()
sample_subset_list <- c(ps1, ps2)

我试过:

formula <- c("~ SampleType", NULL)

> formula
[1] "~ SampleType"

ordination_list <- list()
    for (current_formula in formula) {
                            tmp <- lapply(sample_subset_list, 
                                          ordinate, 
                                          method = "CCA",
                                          formula = as.formula(current_formula))
                            ordination_list[[paste(current_formula)]] <- tmp
}

这样,formula只包含“~ SampleType”。如果我将 NULL 放入刻度,它会被错误地解释为公式:

formula <- c("~ SampleType", "NULL")
Error in parse(text = x, keep.source = FALSE)

解决这个问题的正确方法是什么?

关于Lyzander的回答:

# make sure to use (as suggested)
formula <- list("~ SampleType", NULL)
# and not 
formula <- list()
formula <- c("~ SampleType", NULL)

标签: rfunctionfor-loop

解决方案


您可以使用 alist代替:

formula <- list("~ my_constraint", NULL)

# for (i in formula) print(i)
#[1] "~ my_constraint"
#NULL

如果您的函数NULL作为函数的参数,您还应该这样做:

ordination_list <- list()
for (current_formula in formula) {
  tmp <- lapply(sample_subset_list, 
                ordinate, 
                method = "CCA",
                formula = if (is.null(current_formula)) NULL else as.formula(current_formula))
  ordination_list[[length(ordination_list) + 1]] <- tmp
}

推荐阅读