Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I assign a function with ifelse in 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 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?

like image 550
quazgar Avatar asked Feb 05 '14 12:02

quazgar


2 Answers

@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
like image 40
merv Avatar answered Oct 15 '22 04:10

merv


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]]
like image 127
quazgar Avatar answered Oct 15 '22 05:10

quazgar