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.
Use the IF function, one of the logical functions, to return one value if a condition is true and another value if it's false. For example: =IF(A2>B2,"Over Budget","OK")
Multiple Conditions To join two or more conditions into a single if statement, use logical operators viz. && (and), || (or) and ! (not). && (and) expression is True, if all the conditions are true.
if vs if elseIn if, the statements inside the if block executes if the expression is true. If the expression is false the next statement after the if block executes. In if else, the if block executes if the expression is true and if the expression is false the control is passed to the else block.
In R, the ifelse() function is a shorthand vectorized alternative to the standard if...else statement. Most of the functions in R take a vector as input and return a vectorized output. Similarly, the vector equivalent of the traditional if...else block is the ifelse() function.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With