[R] POURRIEL ifelse and "&&" vs "&"

Toby Marthews Toby.Marthews at lsce.ipsl.fr
Wed Jun 18 15:36:25 CEST 2008


Hi there,

Simplifying your example a bit, we have:

> a=data.frame(r=c(0,0,1,1),g=c(0,1,0,1))
> transform(a,R=(r>0 && g>0))
  r g     R
1 0 0 FALSE
2 0 1 FALSE
3 1 0 FALSE
4 1 1 FALSE
> transform(a,R=(r>0 & g>0))
  r g     R
1 0 0 FALSE
2 0 1 FALSE
3 1 0 FALSE
4 1 1  TRUE
>

...but actually, in the && case the R column values are not calculated
from the corresponding values of r and g: the FALSE is effectively
calculated in row 1 and then copied down. Compare with this:

> a=data.frame(r=c(1,1,0,0),g=c(1,0,1,0))
> transform(a,R=(r>0 && g>0))
  r g    R
1 1 1 TRUE
2 1 0 TRUE
3 0 1 TRUE
4 0 0 TRUE
> transform(a,R=(r>0 & g>0))
  r g     R
1 1 1  TRUE
2 1 0 FALSE
3 0 1 FALSE
4 0 0 FALSE
>

This is actually explained in the ?!base man page: "& and && indicate
logical AND and | and || indicate logical OR. The shorter form performs
elementwise comparisons in much the same way as arithmetic operators. The
longer form evaluates left to right examining only the first element of
each vector. Evaluation proceeds only until the result is determined."

Hope this helps,

Toby Marthews


Le Mer 18 juin 2008 15:10, Christos Argyropoulos a écrit :
>
> Hi,
>
> I noticed whether some one could explain why "&" and "&&" behave
> differently in data frame transformations.
>
> Consider the following :
>
> a<-data.frame(r=c(0,0,2,3),g=c(0,2,0,2.1))
>
> Then:
>
>> transform(a,R=ifelse(r>0 && g> 0,log(r/g),NA))
>
>   r   g  R
> 1 0 0.0 NA
> 2 0 2.0 NA
> 3 2 0.0 NA
> 4 3 2.1 NA
>
> but
>
>> transform(a,R=ifelse(r>0 & g> 0,log(r/g),NA))
>   r   g         R
> 1 0 0.0        NA
> 2 0 2.0        NA
> 3 2 0.0        NA
> 4 3 2.1 0.3566749
>
>
> If my understanding of the differences between "&" and "&&" and how
> 'transform' works are accurate, both statements should produce the same
> output.
>
>
> I got the same behaviour in Windows XP Pro 32-bit (running R v 2.7) and
> Ubuntu Hardy (running the same version of R).
>
>
> Thanks
>
> Christos Argyropoulos
>
> University of Pittsburgh Medical Center



More information about the R-help mailing list