Skip to content
Prev 146043 / 398500 Next

help understanding why #function(x, y) (if((x-y)>=0) {2^(x-y)} else{-(2^abs(x-y))})# doesn't work like I think it should

Use ifelse() rather than if () {} else {}. It's vectorized and very
useful for applying to elements along vectors. The latter idiom is much
better for control of flow in programs and functions.

 folds <- function (x, y) ifelse(x-y >= 0, 2^(x-y), -(2^abs(x-y)))

 z <- folds(x, y)
[1]   16    1    4    4   -4    4 -256
?function works for me. Here's my setup:

R version 2.7.0 (2008-04-22) 
x86_64-pc-linux-gnu 

Cheers,

Simon.
On Tue, 2008-06-03 at 20:47 -0500, ALAN SMITH wrote: