Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ifelse() with three conditions

Tags:

r

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.

like image 381
upabove Avatar asked Sep 02 '13 11:09

upabove


People also ask

What is the syntax of Ifelse () function?

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

How do you write multiple conditions in an if statement in R?

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.

What is the difference between Ifelse () and if else }?

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.

How does Ifelse work in R?

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.


2 Answers

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.

like image 82
Rob Avatar answered Oct 11 '22 11:10

Rob


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.

like image 37
Sven Hohenstein Avatar answered Oct 11 '22 11:10

Sven Hohenstein