Thursday, 19 September 2013

How to prevent NULL from killing my ifelse vectorising?

How to prevent NULL from killing my ifelse vectorising?

I would like to vectorize such function:
if (i > 0)
fun1(a[i])
else
fun2(i)
where fun1, fun2 are already vectorized, and a is a vector.
My attempt:
ifelse(i > 0, fun1(a[i]), fun2(i))
However it is wrong!
> a <- c(1,2,3,4,5)
> i<-c(0,1,2,3)
> ifelse(i > 0, a[i], 0)
[1] 0 2 3 1 # expected 0 1 2 3
Do I have to use sapply? Is there any simple alternative that works?

No comments:

Post a Comment