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

Chose a function with apply() based on some condition

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.

你能帮我正确地应用条件来选择一个函数吗?

这应该有效:

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 是一个函数,它接受一个向量并对其应用逻辑条件,而 returns 一个包含某个指定值(如果该元素的条件为真)或另一个指定值的向量如果该元素的条件为假。在 R 中编程时,单独的 if else 运算符用于条件。有时它们可​​以互换,有时则不能。