Reassembling logical operations on boolean vectors in Gnu R
What a headline.. It’s about combining boolean vectors in R.
I just had some problems with computing a boolean vector as a result of applying AND
to two boolean vectors:
> x <- c(FALSE, TRUE, FALSE)
> y <- c(TRUE, TRUE, FALSE)
> x&&y
[1] FALSE
As you can see, it’s a nice result, but not what I want.. My hack was the following:
> # logical AND
> as.logical(x*y)
[1] FALSE TRUE FALSE
> # logical OR
> as.logical(x+y)
[1] TRUE TRUE FALSE
When Rumpel, my personal R-freak, saw that hack, he just laughed and told me the short version of this hack:
> # logical AND
> x&y
[1] FALSE TRUE FALSE
> # logical OR
> x|y
[1] TRUE TRUE FALSE
Nice, isn’t it ;)
Leave a comment
There are multiple options to leave a comment:
- send me an email
- submit a comment through the feedback page (anonymously via TOR)
- Fork this repo at GitHub, add your comment to the _data/comments directory and send me a pull request
- Fill the following form and Staticman will automagically create a pull request for you:
3 comments
The Rumpel solution is like the syntax in other languages. && is the bitwise operator und & ist the logical operator. The behavior with vectors is specific for the languages. I think matlab has a similar syntax. You need more languages in your head. I need a bag with english knowledge :P
Michael is perfectly right, it’s just the other way round (&& is the logical “and”, & the bitwise).
Thanks to both of you, sometimes I miss the wood for the trees (-;