Re: [R] ifelse and "&&" vs "&

From: Gustaf Rydevik <gustaf.rydevik_at_gmail.com>
Date: Wed, 18 Jun 2008 15:47:02 +0200

On Wed, Jun 18, 2008 at 3:10 PM, Christos Argyropoulos <argchris_at_hotmail.com> wrote:
>
> 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
> _________________________________________________________________

from ?"&" : " 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. "

Thus,

> a$r & a$g

[1] FALSE FALSE FALSE TRUE
> a$r && a$g

[1] FALSE ifelse takes a vector as argument. isince && only gives a single value, ifelse(r>0 && g> 0,log(r/g),NA) will only return NA, which then is recycled by transform. When using &, ifelse returns a vector, and this vector is appended to the data frame.

/Gustaf

-- 
Gustaf Rydevik, M.Sci.
tel: +46(0)703 051 451
address:Essingetorget 40,112 66 Stockholm, SE
skype:gustaf_rydevik

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Wed 18 Jun 2008 - 15:01:55 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 18 Jun 2008 - 15:30:47 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive