Reputation: 21727
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?
Upvotes: 1
Views: 532
Reputation: 12819
There is nothing wrong. a[i]
evaluates to c(1,2,3)
since a[0]
is ignored. this is recycled to c(1,2,3,1)
to match length(i)
. So you get 0 2 3 1
from your ifelse
because the first element of i
is FALSE
, and the other come from a[i]
recycled.
There is a workaroud though: you can replace non-positive indices with NA
:
> ifelse(i > 0, a[ifelse(i > 0, i, NA)], 0)
[1] 0 1 2 3
Upvotes: 3