R如何将NULL传递给可选参数以起作用(例如在for循环中)

时间:2018-11-30 14:23:09

标签: r function for-loop

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

排序功能包含可选参数formula,我想在有或没有公式的情况下执行我的命令。我假设NULL是不使用formula参数的正确方法吗?但是在使用for循环(或应用等)时如何传递NULL

使用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)

1 个答案:

答案 0 :(得分:1)

您可以改用b-navbar-toggle

<b-navbar toggleable="md" type="dark" variant="info">
  <b-navbar-brand href="#">NavBar</b-navbar-brand>

  <!-- Put the toggle here after the brand -->
  <b-navbar-toggle target="nav_collapse"></b-navbar-toggle>

  <b-collapse is-nav id="nav_collapse">

    <b-navbar-nav>
      <b-nav-item href="#">Link</b-nav-item>
      <b-nav-item href="#" disabled>Disabled</b-nav-item>
    </b-navbar-nav>

    <!-- Right aligned nav items -->
    <b-navbar-nav class="ml-auto">

      <b-nav-form>
        <b-form-input size="sm" class="mr-sm-2" type="text" placeholder="Search"/>
        <b-button size="sm" class="my-2 my-sm-0" type="submit">Search</b-button>
      </b-nav-form>

      <b-nav-item-dropdown text="Lang" right>
        <b-dropdown-item href="#">EN</b-dropdown-item>
        <b-dropdown-item href="#">ES</b-dropdown-item>
        <b-dropdown-item href="#">RU</b-dropdown-item>
        <b-dropdown-item href="#">FA</b-dropdown-item>
      </b-nav-item-dropdown>

      <b-nav-item-dropdown right>
        <!-- Using button-content slot -->
        <template slot="button-content">
          <em>User</em>
        </template>
        <b-dropdown-item href="#">Profile</b-dropdown-item>
        <b-dropdown-item href="#">Signout</b-dropdown-item>
      </b-nav-item-dropdown>
    </b-navbar-nav>

  </b-collapse>


</b-navbar>

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

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

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