logical AND (& , &&)  ,  logical OR (| and || )

Published by onesixx on

https://csgillespie.wordpress.com/2010/12/14/logical-operators-in-r/

double operator이 필요한 경우.
To be honest, I’m not sure. I can think of a few contrived situations,
but nothing really useful.

The R help page isn’t that enlightening either.
.
This has two benefits:

Evaluation will be faster. In the above example, the function g isn’t evaluated (thanks to Andrew Robson and NotMe)
Also, you can use the double variety to check a property of a data structure before carrying on with your analysis, i.e. all(!is.na(x)) && mean(x) > 0 (thanks to Pat Burns for this tip)

> z <-  1:6
> z
[1] 1 2 3 4 5 6
> (z > 2)
[1] FALSE FALSE  TRUE  TRUE  TRUE  TRUE
> (z < 5)
[1]  TRUE  TRUE  TRUE  TRUE FALSE FALSE
> (z > 2) & (z < 5)
[1] FALSE FALSE  TRUE  TRUE FALSE FALSE
> z[(z>2) & (z<5)]
[1] 3 4



> (z > 2) && (z < 5)
[1] FALSE
> z[(z > 2) && (z < 5)]
integer(0)
> (z > 2) && (z < 5)
[1] FALSE
> z[(z > 0) && (z < 5)]
[1] 1 2 3 4 5 6


>   
> (z > 0) && (z < 5)
[1] TRUE
> (z > 0) && (z < 5)
[1] TRUE
> (z > 0)
[1] TRUE TRUE TRUE TRUE TRUE TRUE
> (z < 5)
[1]  TRUE  TRUE  TRUE  TRUE FALSE FALSE
> (z[1] > 2) & (z[1] < 5)
[1] FALSE
https://stackoverflow.com/questions/6558921/r-boolean-operators-and
http://www.burns-stat.com/pages/Tutor/R_inferno.pdf
http://stat.ethz.ch/R-manual/R-patched/library/base/html/Logic.html

 

logical AND (& , &&)  ,  logical OR (| and || )

&& 

결과가 하나, 왼쪽에서 오른쪽으로 단지 Vector의 첫번째 요소만 비교한다. 

((-2:2) >= 0) && ((-2:2) <= 0)
[1] FALSE

-2 -2 FALSE

Help 페이지를 보면, 
&& || 는  "appropriate for programming control-flow and [is] typically preferred in if clauses." 라고 쓰여있다. 
즉 length()가 1인 vector일때 사용하는 것이 헷갈리지 않는다.
결과도 당연히 1개의 boolean이 나온다. 

결과가 여러개,  vectorized 비교,  결과적으로 vector를 return한다. 

((-2:2) >= 0) & ((-2:2) <= 0)
[1] FALSE FALSE  TRUE FALSE FALSE

-2 -2 FALSE
-1 -1 FALSE
 0  0 TRUE
 1  1 FALSE
 2  2 FALSE

vectors의 length가 1보다 크게 나올수 있을 경우 사용한다.
all과 any 함수와 함께 사용하여 결과를 하나의 boolean값으로 만들어 vectorized comparison수행하는 경우가 많다. 

예> 정의되지 않은 (Undefined) 값인 a에 대해서  For example, here's a comparison using an undefined value a;
if it didn't short-circuit, as & and | don't, it would give an error.

a
# Error: object 'a' not found
TRUE | a
# Error: object 'a' not found

FALSE & a
# Error: object 'a' not found
TRUE || a
# [1] TRUE

FALSE && a
# [1] FALSE

 

Categories: R Reshaping

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x