[R] Can anyone help why the errors are coming and rectify it?

(Ted Harding) Ted.Harding at wlandres.net
Mon Sep 17 13:29:49 CEST 2012


On 17-Sep-2012 09:47:41 Sri krishna Devarayalu Balanagu wrote:
> Hi Everyone,
> Can anyone help why the errors are coming and rectify it?
> 
> invalid.ids <- c(1,3,5)
> if (length(invalid.ids)==0)   {
>                                                                              
> cat("No Errors found")
>                                                        }
> else                                              {
>                                                                              
> cat(paste(invalid.ids), sep="\n")
>                                                       }
> 
> Error: unexpected 'else' in "else"
> Error: unexpected '}' in "        }"
> 
> Thank you in advance
> 
> Warm Regards
> Rayalu

Reformatting your code (for readability) but preserving your
line breaks:

  invalid.ids <- c(1,3,5)
  if (length(invalid.ids)==0) {
    cat("No Errors found")
  }
  else {
    cat(paste(invalid.ids), sep="\n")
  } }

  Error: unexpected 'else' in "else"
  Error: unexpected '}' in "        }"

First:

The first four lines are a completed command, given the way
that R parses input. After encountering the end-of-line at
the fourth line, R considers that it has seen a complete command
and therefore executes it.

 invalid.ids <- c(1,3,5)
  if (length(invalid.ids)==0) {
    cat("No Errors found")
  }

Therefore the "else {" on the next line is not interpreted as
if it were part of the preceding "if()" statement, since that
has been considered complete and has been executed. So that
"else" is an "else" with no matching "if". Henc the the first
error message.

Second: if you count the opening "{" and closing "}", you will
see that there is one "}" too many, at the end, hence the second
error message.

The way to avoid the first error message is to put the "else"
on the same line as the close of the "if" statement. Then R will
recognise that it has an incomplete commend, and continue to parse
further input until it has built up a complete command. So you
should write:

  invalid.ids <- c(1,3,5)
  if (length(invalid.ids)==0) {
    cat("No Errors found")
  } else {
    cat(paste(invalid.ids), sep="\n")
  }

(Note that the extra "}" has been omitted too).

Hoping this helps,
Ted.


-------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at wlandres.net>
Date: 17-Sep-2012  Time: 12:29:46
This message was sent by XFMail




More information about the R-help mailing list