andreas at jostel.com
2007-Apr-02 07:17 UTC
[R] ?Bug: '&&' and '&' give different results?
"&&" seems to behave strangely and gives different results
from "&" e.g. in a data frame selection (regardless whether terms
are bracketed)?
===========Script======================
test=data.frame(gender=c("F","M","M","F","F"),side=c("R","L","R","L","R"))
test
test[test$gender=="F" & test$side=="R",]
test[test$gender=="F" && test$side=="R",]
=============Output:====================>
test=data.frame(gender=c("F","M","M","F","F"),side=c("R","L","R","L","R"))> test
gender side
1 F R
2 M L
3 M R
4 F L
5 F R> test[test$gender=="F" & test$side=="R",]
gender side
1 F R
5 F R> test[test$gender=="F" && test$side=="R",]
gender side
1 F R
2 M L
3 M R
4 F L
5 F R
As the help page says:
'&' 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.
The longer form is appropriate for programming control-flow and
typically preferred in 'if' clauses.
so your results are what I'd expect.
Ted.
andreas at jostel.com wrote on 04/02/2007 05:17 PM:> "&&" seems to behave strangely and gives different
results from "&" e.g. in a data frame selection (regardless
whether terms are bracketed)?
>
> ===========Script======================>
>
test=data.frame(gender=c("F","M","M","F","F"),side=c("R","L","R","L","R"))
> test
> test[test$gender=="F" & test$side=="R",]
> test[test$gender=="F" && test$side=="R",]
>
> =============Output:====================>
>>
test=data.frame(gender=c("F","M","M","F","F"),side=c("R","L","R","L","R"))
>> test
>>
> gender side
> 1 F R
> 2 M L
> 3 M R
> 4 F L
> 5 F R
>
>> test[test$gender=="F" & test$side=="R",]
>>
> gender side
> 1 F R
> 5 F R
>
>> test[test$gender=="F" && test$side=="R",]
>>
> gender side
> 1 F R
> 2 M L
> 3 M R
> 4 F L
> 5 F R
>
> ______________________________________________
> 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
> and provide commented, minimal, self-contained, reproducible code.
>
--
Dr E.A. Catchpole
Visiting Fellow
Univ of New South Wales at ADFA, Canberra, Australia
_ and University of Kent, Canterbury, England
'v' - www.pems.adfa.edu.au/~ecatchpole
/ \ - fax: +61 2 6268 8786
m m - ph: +61 2 6268 8895