I am confused about the operator & and && in R, which one should I use?

It turns out:

"The shorter ones are vectorized, meaning they can return a vector, The longer form evaluates left to right examining only the first element of each vector"

an example would suffice to explain it.

> x<-c(1:10)

> x

[1] 1 2 3 4 5 6 7 8 9 10

> x>8

[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE

> logical1<- x>8

> logical2<- x<5

> logical1

[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE

> logical2

[1] TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE

> logical1 | logical2

[1] TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE TRUE TRUE

> logical1 & logical2

[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

> logical1 && logical2

[1] FALSE

one can subset the vector by the logical vectors:

> x[logical1]

[1] 9 10

> x[logical2]

[1] 1 2 3 4

Correct. Approved ! :_)

ReplyDelete