[R] Error in if loop
Mark Wardle
mark at wardle.org
Sun Oct 21 17:08:40 CEST 2007
On 21/10/2007, stat stat <stat700004 at yahoo.co.in> wrote:
> I have created a if loop as follows:
>
> name = "e"
> if (name == "v")
> {
> u = 0
> }
> else u = 1
>
> however i am getting error : Error: unexpected 'else' in "else"
There are 3 issues here:
1. Do you appreciate the difference between ifelse and if ? What are
you actually trying to do - in this context, ifelse would usually be
more sensible but as you've not said what you want to do, it is
difficult to guess.
2. I don't get the same error as you. Which version of R are you using?
> if (name=="v")
+ {
+ u=0
+ }
> else u=1
Error: syntax error
This error message makes it clear that there is a syntax problem. In
fact, look at the lefthand column of characters and you should see
what the problem is....
3. R is interpreting your code as two separate expressions because you
are using an interactive shell. Try this instead:
if (name=='v') {
u=1
} else {
u=0
}
Hope this helps.
Best wishes,
Mark
--
Dr. Mark Wardle
Specialist registrar, Neurology
Cardiff, UK
More information about the R-help
mailing list