BlackHat
BlackHat

Reputation: 755

Multiple If Statements in R

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.

Upvotes: 15

Views: 102380

Answers (2)

via Chris.
via Chris.

Reputation: 196

A simple solution is to use a compound statement wrapped in braces, putting the else on the same line as the closing brace that marks the end of the statement, as below:

if (condition 1) {
    statement 1
} else if (statement 2) {
    statement 2
} else {
    statement 3
}

If your if statement is not in a block, then the else statement must appear on the same line as the end of statement 1 above. Otherwise, the new line at the end of statement 1 completes the if and yields a syntactically complete statement that is then evaluated.

The above is more or less a quote from section 3.2.1. in the R language definition (http://cran.r-project.org/doc/manuals/R-lang.pdf). Hope that helps :)

Upvotes: 15

Mamoun Benghezal
Mamoun Benghezal

Reputation: 5314

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}

Upvotes: 26

Related Questions