Why can't I assign an ifelse function to R?

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

 attempt to replicate an object of type 'closure' 

What can I do to assign one of two functions to a variable and what happens here?

+7
r functional-programming
source share
2 answers

Since ifelse vectorized and does not provide special cases for non-vectorized conditions, the arguments are replicated using rep(...) . rep(...) does not work for closures, for example, in the example.

A workaround would be to temporarily terminate the functions:

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

@ Joshua Ulrich's comment is the correct answer. The correct way to do conditional function assignment is the classic if...else , and not the vector ifelse method:

 my.func <- if (cond) sqrt else identity 
+1
source share

All Articles