Home > Mobile >  Chose a function with apply() based on some condition
Chose a function with apply() based on some condition

Time:10-11

In apply() function, I need to provide a function name. But in my case, that function name needs to be based on some other condition. Below is such example:

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

However with this I am getting below error:

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.

Can you please help me on right way to apply condition to chose a function.

CodePudding user response:

This should work:

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 is a function that takes a vector and applies a logical condition to it, and returns a vector containing some specified value if that condition is true for that element, or another specified value if that condition is false for that element. The separate if else operators are used for conditionals when programming in R. Sometimes they're interchangeable and sometimes they're not.

  • Related