[R] Error in if loop
Mark Wardle
mark at wardle.org
Sun Oct 21 23:06:37 CEST 2007
No.
Think of "if" only as a means to control program flow.
Use ifelse to use conditional logic on each item of a vector
Best wishes,
Mark
On 21/10/2007, stat stat <stat700004 at yahoo.co.in> wrote:
> Dear Mark,
>
> Thanks for this. Can you please explain me what is the difference between
> ifelse and if?
> generally if there is more than one syntax within the 'if' I use 'if' loop
> otherwise I use 'ifelse' loop. Is it the only difference between them?
>
>
> Mark Wardle <mark at wardle.org> wrote:
> On 21/10/2007, stat stat 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
>
>
>
> thanks in advance
>
> ________________________________
> Forgot the famous last words? Access your message archive online. Click
> here.
> ______________________________________________________________________
> This email has been scanned by the MessageLabs Email Security System.
> For more information please visit
> http://www.messagelabs.com/email
> ______________________________________________________________________
>
--
Dr. Mark Wardle
Specialist registrar, Neurology
Cardiff, UK
More information about the R-help
mailing list