13

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.

BlackHat
  • 736
  • 1
  • 10
  • 24
  • 2
    possible duplicate of [if - else if - else statement and brackets](http://stackoverflow.com/questions/25885358/if-else-if-else-statement-and-brackets) – zx8754 Jul 07 '15 at 07:18
  • you're testing the same thing several times. You can rather do `if(exists("A")) { if(exits("B")) {C <- rbind(B, A)} else {C <- A} } else {if(exits("B")) {C <- B} else { C <- NULL} }` or even `okA <- exists("A") ; okB <- exists("B")` and use those in the above line – Cath Jul 07 '15 at 07:29
  • you can also [use cases function](http://stackoverflow.com/a/4628810/4137985) to avoid the multiple if/else statements – Cath Jul 07 '15 at 07:31

2 Answers2

24

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}
Mamoun Benghezal
  • 5,264
  • 7
  • 28
  • 33
14

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

via Chris.
  • 186
  • 4