Brian Smith
Brian Smith

Reputation: 1353

Chose a function with apply() based on some condition

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.

Upvotes: 0

Views: 47

Answers (1)

henryn
henryn

Reputation: 1237

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.

Upvotes: 1

Related Questions