Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
690 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...