Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
683 views
in Technique[技术] by (71.8m points)

vector - The difference between & and && in R

I have read

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

and the difference between & and && doesn't make sense. For example :

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

According to the link this is expected behavior. It is doing an element-wise comparison of the two vectors.

So I test again...

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

This also returns what was expected.

But then I change a value...

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

Still expected because it 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

& is a logical operator so R coverts your quantities to logical values before comparison. For numeric values any non-0 (and non-NA/Null/NaN stuff) gets the value TRUE and 0 gets FALSE. So with that said things make quite a bit of sense

> 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...