0

The && boolean operator seems to work differently with character vectors and I was wondering if anyone knows why.

For example:

streetA <- c("green", "green", "red")

streetB <- c("green", "green", "green")

streetA == "green" && streetB == "green"

returns TRUE, but the statement should return FALSE since streetA has a "red" in it.

The & statement works as expected:

streetA == "green" & streetB == "green"

returns: TRUE TRUE FALSE

Does anyone know why this is?

Bob M
  • 31
  • 1
  • 2
  • 7
  • "The && boolean operator seems to work differently with character vectors" : different compared to what? That's expected behavior. – Dason Feb 27 '19 at 02:10
  • [Logical AND](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Logic.html) "evaluates left to right examining only the first element of each vector". Try changing the first "green" in one of the vectors to "blue"; you'll get FALSE. – neilfws Feb 27 '19 at 02:12
  • Different compared to integer values. It's an and operator so it should on return TRUE if all are true. OR || returns TRUE if one side is TRUE – Bob M Feb 27 '19 at 02:13
  • Nope. Integer vectors work the same way with these operators. – Dason Feb 27 '19 at 02:15
  • Yup, you're right. For some reason, I thought the operator did a pairwise comparison and broke once it got its first FALSE. – Bob M Feb 27 '19 at 02:18
  • You might be interested in `all()` and `any()`. Seems like you're aiming for `all(streetA == "green") && all(streetB == "green")`. – Gregor Thomas Feb 27 '19 at 02:51
  • You are absolutely right, Gregor! That is what I was looking for. Thank you, everyone, for your help and input on this. – Bob M Feb 27 '19 at 19:25

1 Answers1

4

From the && documentation:

& and && indicate logical AND and | and || indicate logical OR. The shorter form performs elementwise comparisons in much the same way as arithmetic operators. The longer form evaluates left to right examining only the first element of each vector. Evaluation proceeds only until the result is determined. The longer form is appropriate for programming control-flow and typically preferred in if clauses.

dylanjm
  • 2,011
  • 9
  • 21