[R] if statement

(Ted Harding) Ted.Harding at wlandres.net
Wed Mar 7 20:46:08 CET 2012


The simplest method would be:

  x[x<0] <- x[x<0]+1

  x <- -1:4
  x
  # [1] -1  0  1  2  3  4
  x[x<0] <- x[x<0]+1
  x
  # [1] 0 0 1 2 3 4

I think where Val got confused is in thinking that

  if(x<0)

is applied separately to each element of x, one at a time.

What actually happens, of course, is that "x<0" is evaluated
for each element of x (vectorially), giving

  x <- -1:4
  x<0
  # [1]  TRUE FALSE FALSE FALSE FALSE FALSE

and now the "if(x<0) x <- x+1" is, in effect,

  if(c(TRUE,FALSE,FALSE,FALSE,FALSE,FALSE)) x <- x+1

Hence the error message: if(...) expects a *single* TRUE
or FALSE argument, not a string of them; so, if given a string,
it picks the first, finds that it is TRUE, and so executes
  x <- x+1
which adds 1 to every element of x.

>From ?"if":

  if(cond) expr
  cond: A length-one logical vector that is not 'NA'.
    Conditions of length greater than one are accepted
    with a warning, but only the first element is used.
    Other types are coerced to logical if possible,
    ignoring any class.

On the other hand, x[x<0] selects those elements of x for
which "x<0" is TRUE, hence

  x[x<0] <- x[x<0]+1

is a vectorial operation on those elements of x for which
"x<0" is TRUE, so each such element is replaced by 1 plus
that same element.

Hoping this helps,
Ted.

On 07-Mar-2012 Sarah Goslee wrote:
> You need ifelse() instead of if().
> 
> On Wed, Mar 7, 2012 at 2:12 PM, Val <valkremk at gmail.com> wrote:
>> Hi All,
>>
>> I have one difficulty in using the conditional if statement
>>
>> Assume ,
>>
>> x <- -1:4
>> x
>> [1] -1 0 1 2 3 4
>>
>> if x is lees than want I want to add 1 and I used the following command
>> if(x<0) {x=x+1}
>>
>> Warning message:
>> In if (x < 0) { :
>> the condition has length > 1 and only the first element will be used
>>> x
>> [1] 0 1 2 3 4 5
>> That command added 1 to each element.
>>
>> But I want like this _0 0 1 2 3 4
>>
>> Can anybody help me?
>>
>> Thanks
>> Val
> -- 
> Sarah Goslee
> http://www.functionaldiversity.org

-------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at wlandres.net>
Date: 07-Mar-2012  Time: 19:46:05
This message was sent by XFMail



More information about the R-help mailing list