[R] zero index and lazy evaluation in ifelse()

Uwe Ligges ligges at statistik.uni-dortmund.de
Thu Jan 13 23:11:48 CET 2005


White.Denis at epamail.epa.gov wrote:

> This seems to contradict the help file.
> 
> "... 'yes' will be evaluated if and only if any element of 'test' is
> true,
> and analogously for 'no'..."


Note: "Evaluated", not "returned"!
So both "0" and "b[a]" are evaluated, because a==0 is true for a[1], and 
false for a[2], a[3], a[4].

a[1] == 0 is true, hence you get "0",
a[2] == 0 is false, hence you get b[a][2]=2
a[3] == 0 is false, hence you get b[a][3]=3
a[4] == 0 is false, hence you get b[a][4], which is recycled to b[a][1]=1

Uwe Ligges


> 
> Peter Dalgaard <p.dalgaard at biostat.ku.dk> wrote on 2005-01-13 13:24:31:
> 
> 
>>White.Denis at epamail.epa.gov writes:
>>
>>
>>>I don't understand this behavior:
>>>
>>>
>>>>a <- c(0, 1, 2, 3)
>>>>b <- c(1, 2, 3, 4)
>>>>ifelse (a == 0, 0, b[a])
>>>
>>>[1] 0 2 3 1
>>>
>>>rather than the desired 0 1 2 3.  Thanks for any explanation.
>>
>>b[a] is c(1,2,3), recycling to length 4 gives c(1,2,3,1), get it?
>>
>>--
>>   O__  ---- Peter Dalgaard             Blegdamsvej 3
>>  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N
>> (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45)
> 
> 35327918
> 
>>~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45)
> 
> 35327907
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html




More information about the R-help mailing list