[Rd] ifelse() woes ... can we agree on a ifelse2() ?

S Ellison S.Ellison at LGCGroup.com
Sat Nov 26 19:52:15 CET 2016


> Just stating, in 'ifelse', 'test' is not recycled. As I said in "R-intro: length of 'ifelse' result" 
> (https://stat.ethz.ch/pipermail/r-devel/2016-September/073136.html), ifelse(condition, a, b) 
> returns a vector of the length of 'condition', even if 'a' or 'b' is longer.

That is indeed (almost) the documented behaviour. The documented behaviour is slightly more complex; '... returns a value _of the same shape_ as 'test''. IN principle, test can be a matrix, for example.

> A concrete version of 'ifelse2' that starts the result from 'yes':
> .. still a bit disappointed that nobody has taken a look ...

I took a look. The idea leaves (at least) me very uneasy. If you are recycling 'test' as well as arbitrary-length yes and no, results will become frighteningly hard to predict except in very simple cases where you have well-defined and consistent regularities in the data. And where you do, surely passing ifelse a vetor of the right length, generated by rep() applied to a short 'test' vector, will do what you want without messing around with new functions that hide what you're doing.

Do you really have a case where 'test' is neither a single logical (that could be used with 'if') nor a vector that can be readily replicated to the desired length with 'rep'?

If not, I'd drop the attempt to generate new ifelse-like functions. 

S Ellison



*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}



More information about the R-devel mailing list