Spaceship222
Spaceship222

Reputation: 849

A confusion about `ifelse`

There is a confusion about ifelse.I hope someone can help explain.
Consider code below:

x1 = c(1,4,3)
y1 = c(2,3,5)
# 1
> ifelse(x1 > y1, x1^2 + y1^2,y1)
[1]  2 25  5

# 2
> ifelse(x1 > y1, sum(x1),y1)
[1] 2 8 5
# from #1 I guess second element should be sum(x1) == sum(x1[2]) == sum(4)  

Why?
Update:
After reading the book -- The Art of R Programming, I solve my problem.

ifelse(b,u,v) where b is a Boolean vector, and u and v are vectors. The return value is itself a vector; element i is u[i] if b[i] is true, or v[i] if b[i] is false

So

ifelse(x1 > y1, sum(x1),y1) == ifelse(x1 > y1, c(sum(x1),sum(x1),sum(x1)),c(2,3,5))  # by recycling
# then b = c(T,F,T), u = c(8,8,8), v = c(2,3,5)
# therefore output would be (v[1],u[2],v[3]), i.e.
# [1] 2 8 5

Upvotes: 2

Views: 67

Answers (1)

safex
safex

Reputation: 2514

sum(x1)=8 is obvious since 1+4+3=8. Now you might wonder why ifelse seems to evaluate expressions differently: It is not, it is just that ^2 cannot be applied to a vector (whats a vector squared?) so it is applying element wise. you can however apply sum() to a vector, which happens in the second evaluation. try ifelse(x1 > y1, x1,y1)

Upvotes: 1

Related Questions