2

I have the following code/pseudocode:

    if (condition A)
        {
          if(condition B)
             {
               print("Yes")
             }
          else 
            {
               print("No")
            }

         }
   else
       {
         print("Maybe")
       }

Why does R say the last else is an unexpected token?

user21478
  • 155
  • 2
  • 3
  • 10
  • Please add a reproducible example so that it is easy to help you. Moreover, that thing is most likely because of https://stackoverflow.com/questions/25889234/error-unexpected-symbol-input-string-constant-numeric-constant-special-in-my-co – Ronak Shah Apr 10 '18 at 04:15
  • Put it on the same line as the previous closing brace, as in `} else {` instead of `}\n else`. (It's a parser thing, where the newline after the `}` causes it to infer that it should expect a "new/fresh" command, not a command-continuance like `else`.) – r2evans Apr 10 '18 at 04:19
  • 1
    ... though I like that link that @RonakShah provided, citing *Prophylactic measures to prevent you getting the error again*. Nice (and a good read for all aspiring programmers in R)! – r2evans Apr 10 '18 at 04:21
  • all of your questions have answers, and you have checked _one_ of them. also please follow this style guide https://google.github.io/styleguide/Rguide.xml – rawr Apr 10 '18 at 04:32

1 Answers1

1

Compare:

if (1 > 2){
  print("Yes")
}  # this if statement ends here, then the else throws an error
else {
  print("No")
}

Error: unexpected 'else' in "else"

With:

if (1 > 2){
  print("Yes")
} else {
  print("No")
}

[1] "No"

You have to begin your else statement on the same line, otherwise R reads it as two distinct statements, rather than all part of one if statement.

Mako212
  • 6,787
  • 1
  • 18
  • 37