代码之家  ›  专栏  ›  技术社区  ›  Brian Smith

根据某些条件选择了带apply()的函数

  •  0
  • Brian Smith  · 技术社区  · 3 年前

    在里面 apply() 函数,我需要提供一个函数名。但在我的例子中,函数名需要基于其他条件。下面就是这样的例子:

    library(dplyr)
    Function = TRUE
    as.data.frame(matrix(1:12, 4)) %>%
        mutate(Res = apply(as.matrix(.), 1, ifelse(Function, ~mean, ~sd), na.rm = TRUE))
    

    然而,我发现以下错误:

    Error: Problem with `mutate()` column `Res`.
    ℹ `Res = apply(as.matrix(.), 1, ifelse(Function, ~mean, ~sd), na.rm = TRUE)`.
    ✖ attempt to replicate an object of type 'language'
    Run `rlang::last_error()` to see where the error occurred.
    

    你能帮我选择一个函数的正确方法吗。

    1 回复  |  直到 3 年前
        1
  •  1
  •   henryn    3 年前

    这应该起作用:

    library(dplyr)
    Function = TRUE
    as.data.frame(matrix(1:12, 4)) %>%
      mutate(Res = apply(as.matrix(.), 1, if (Function) mean else sd, na.rm = TRUE))
    

    ifelse 是一个函数,它接受一个向量并对其应用一个逻辑条件,如果该元素的条件为true,则返回一个包含某个指定值的向量;如果该元素的条件为false,则返回另一个指定值。分离 if else 在R中编程时,运算符用于条件语句。有时它们是可互换的,有时则不是。