The difference between & and && in R

I read

http://stat.ethz.ch/R-manual/R-devel/library/base/html/Logic.html

and the difference between and and && does not make sense. For example:

> c(1, 2, 3) & c(1,2,3)
[1] TRUE TRUE TRUE

According to the link, this is the expected behavior. It performs an elemental comparison of two vectors.

So, I'm testing again ...

> c(1, 2, 3) && c(1,2,3)
[1] TRUE

This also returns the expected.

But then I change the meaning ...

> c(1, 2, 3) && c(1,3,3)
[1] TRUE

Still expected because these are short circuits on the first element.

> c(1, 2, 3) & c(1,3,3)
[1] TRUE TRUE TRUE

This, however, lost me. These two vectors should not be equal.

+4
source share
3 answers

& , R . , 0 ( -NA/Null/NaN), TRUE, 0 FALSE. , , .

> as.logical(c(1,2,3))
[1] TRUE TRUE TRUE
> as.logical(c(1,3,3))
[1] TRUE TRUE TRUE
> as.logical(c(1,2,3)) & as.logical(c(1,2,3))
[1] TRUE TRUE TRUE
> as.logical(c(1,2,3)) & as.logical(c(1,3,3))
[1] TRUE TRUE TRUE
+11

, :

as.logical(c(0,1,2,3,4))
#[1] FALSE  TRUE  TRUE  TRUE  TRUE

...

c(1,2,3) & c(1,3,3)
#[1] TRUE TRUE TRUE

:

c(TRUE,TRUE,TRUE) & c(TRUE,TRUE,TRUE)

... & c(TRUE,TRUE,TRUE)

:

test <- c(NA,NaN,-Inf,-1,-0.5,0,0.5,1,2,Inf)
data.frame(test,as.logical(test))

#   test as.logical.test.
#1    NA               NA
#2   NaN               NA
#3  -Inf             TRUE
#4  -1.0             TRUE
#5  -0.5             TRUE
#6   0.0            FALSE
#7   0.5             TRUE
#8   1.0             TRUE
#9   2.0             TRUE
#10  Inf             TRUE
+9

"&" -by-element , . :

 c(0,1,2,3,4) & 1
[1] FALSE  TRUE  TRUE  TRUE  TRUE  # due to argument recycling

Please note that it does not compare numerical values, but only after being forced to enter β€œlogical”, and any nonzero value will be TRUE:

seq(0,1,by=.2) & -1
[1] FALSE  TRUE  TRUE  TRUE  TRUE  TRUE

"& &" only compares the first element of its first argument with the first argument of the second and gives a warning (but not an error) if it is longer than one element.

If you want to verify equality, use "==".

+6
source

Source: https://habr.com/ru/post/1526098/


All Articles