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?
@Joshua Ulrich's comment is a proper answer. The correct way to accomplish conditional function assignment is a classic if...else
rather than the vectorized ifelse
method:
my.func <- if (cond) sqrt else identity
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With