Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple If Statements in R

Tags:

r

if-statement

I've been trying to figure this out all day but to no avail. I have an if statement that is meant to satisfy four possible conditions.

  1. A exists and B does not exist
  2. B exists and A doesn't exist
  3. A & B exist
  4. A & B do not exist

A, B, C are dataframes.

Here is my code:

if (!exists("A") & exists("B")) {
  C= B} 
else if (exists("A") & !exists("B")) {
  C= A}
else if (exists("A") & exists("B")) {
  C= rbind(B,A)} 
else {C <- NULL}

I keep getting an error on unexpected "}" and unexpected "else". I've followed several examples but still facing this challenge. Any pointers would be much appreciated. Thx.

like image 415
BlackHat Avatar asked Jul 07 '15 07:07

BlackHat


People also ask

Can you have multiple else if statements in R?

The if-else statements can be nested together to form a group of statements and evaluate expressions based on the conditions one by one, beginning from the outer condition to the inner one by one respectively.

Can we use 2 if statements?

Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.

Which command R multiple conditions?

Multiple conditions can also be combined using which() method in R. The which() function in R returns the position of the value which satisfies the given condition.

Can you have multiple if statements in a for loop?

You can put a for loop inside an if statement using a technique called a nested control flow. This is the process of putting a control statement inside of another control statement to execute an action. You can put an if statements inside for loops.


1 Answers

try this

if (!exists("A") & exists("B")) {
    C= B
} else if (exists("A") & !exists("B")) {
    C= A
} else if (exists("A") & exists("B")) {
    C= rbind(B,A)
} else {C <- NULL}
like image 195
Mamoun Benghezal Avatar answered Oct 06 '22 16:10

Mamoun Benghezal