[R] if else does not return right value

David Winsemius dwinsemius at comcast.net
Sat Dec 26 19:50:58 CET 2009


See below:

On Dec 26, 2009, at 12:58 PM, Muhammad Rahiz wrote:

> Hi all,
>
> I'm not getting the right results for values that are >99 using the  
> if else function. The following illustrates the problem
>
> > x <- as.matrix(read.table("test.txt"))
> > x
>      V1 V2 V3
> [1,]  47  1 43
> [2,]  83  2 42
> [3,]   1  3 41
> [4,]  39  4 40
> [5,]  23  5 39
> [6,]  23  6 38
> [7,]  39  7 37
> [8,]  32  8 36
> [9,]  73  9 35
> [10,] 124 10 34
>
> Specifying the followng condition,
>
> if ( x <20){
> y <- x +100
> } else {
> y <- x -100
> }
>
> > y
>     V1  V2  V3
> [1,] -53 -99 -57
> [2,] -17 -98 -58
> [3,] -99 -97 -59
> [4,] -61 -96 -60
> [5,] -77 -95 -61
> [6,] -77 -94 -62
> [7,] -61 -93 -63
> [8,] -68 -92 -64
> [9,] -27 -91 -65
> [10,]  24 -90 -66
>
> The output generated contains 'errors.
>
> For example, given that x < 20,
> for x = 1, the output should be x+100 = 1 + 100 = 101.
> However, the generated output is -99.
>
> In addition, there is the following warning message which I don't  
> know what it means
>   the condition has length > 1 and only the first element will be used
>
> The problem is solved if I use the ifelse function but I want to  
> specify the code as following;
>
> if (/condition/) {
> /statement 1a
> statement 1b
> /} else {
> /statement 2a
> statement 2b
> /}

If that is your firm desire, then you need to run an indexed loop or  
an apply function over the individual values of the "if" evaluated on  
contents of x. The "if" function is not vectorized.

y <- apply(x, 1:2,function(xx)
    if (xx <20){
           xx+100
       }else{
           xx-100
      } )

 > y
        V1  V2  V3
  [1,] -53 101 -57
  [2,] -17 102 -58
  [3,] 101 103 -59
  [4,] -61 104 -60
  [5,] -77 105 -61
  [6,] -77 106 -62
  [7,] -61 107 -63
  [8,] -68 108 -64
  [9,] -27 109 -65
[10,]  24 110 -66

>
> Thanks.
>
> Muhammad
>
> --

-- 
David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list