r - 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)
解决方案
您可以使用 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
}
推荐阅读
- typescript - 打字稿:如何在保存记录的结构上“应用”?
- html - 有没有办法一次显示一个记录的列表对象
- ios - SwiftUI:如何从 Slider 获取持续更新
- c++ - 使用 SOLVEPNP_EPNP 的相机姿态估计是否对异常值敏感,可以纠正吗?
- c++ - 优化计算超级数字的递归问题
- javascript - 使用 css 从顶部剪辑图像
- angular - 如何仅在特定路线上显示元素?
- react-native - onSubmitEditing 在每次按键时触发
- c++ - BGR -> YCbCr 转换无法正常工作
- vue.js - 将数据传递给路由的组件 beforeEnter