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
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.
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.
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)