Why can't I assign a function with ifelse in R?

functional-programming, r

Solution

Because `ifelse` is vectorized and does not provide special cases for non-vectorized conditions, the arguments are replicated with `rep(...)`. `rep(...)` fails for closures such as in the example though.

A workaround would be to temprarily wrap the functions:

my.func <- ifelse(cond, c(sqrt), c(identity))[[1]]

Problem

In R, when I try to assign a function via `ifelse`, I get the following error: ``` > my.func <- ifelse(cond, sqrt, identity) Error in rep(yes, length.out = length(ans)) : attempt to replicate an object of type 'builtin' ``` If `cond` is `FALSE`, the error looks equivalent, R complains about an ``` attempt to replicate an object of type 'closure' ``` What can I do to assign one of two functions to a variable and what is going on here?

Original source

Related problems