upabove
upabove

Reputation: 1119

Ifelse() with three conditions

I have two vectors:

a<-rep(1:2,100)

b<-sample(a)

I would like to have an ifelse condition that compares each value of a with the corresponding value of b, and does the following:

if a>b 1
if a<b 0
if a=b sample(1:2,length(a),replace=T)

the first two can be done with :

ifelse(a>b,1,0)

but I'm not sure how to incorporate the case where a and b are equal.

Upvotes: 20

Views: 65677

Answers (3)

Rob
Rob

Reputation: 1490

How about adding another ifelse:

ifelse(a>b, 1, ifelse(a==b, sample(1:2, length(a), replace = TRUE), 0))

In this case you get the value 1 if a>b, then, if a is equal to b it is either 1 or 2 (sample(1:2, length(a), replace = TRUE)), and if not (so a must be smaller than b) you get the value 0.

Upvotes: 34

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

This is an easy way:

(a > b) + (a == b) * sample(2, length(a), replace = TRUE)

This is based on calculations with boolean values which are cast into numerical values.

Upvotes: 10

mpiktas
mpiktas

Reputation: 11518

There is ambiguity in your question. Do you want different random values for all indexes where a==b or one random value for all indexes?

The answer by @Rob will work in the second scenario. For the first scenario I suggest avoiding ifelse:

u<-rep(NA,length(a))
u[a>b] <- 1
u[a<b] <- 0
u[a==b] <- sample(1:2,sum(a==b),replace=TRUE)

Upvotes: 8

Related Questions