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 ;)


Martin Scharm

stuff. just for the records.


3 Comments

Michael Rennecke | Permalink | 2010-10-13 14:54:36

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

Nerd | Permalink | 2010-10-14 09:26:08

Michael is perfectly right, it’s just the other way round (&& is the logical “and”, & the bitwise).

Martin Scharm | Permalink | 2010-10-14 09:48:13

Thanks to both of you, sometimes I miss the wood for the trees (-;

Post a comment

read more about submitting comments