Site icon R-bloggers

Reassembling logical operations on boolean vectors in Gnu R

[This article was first published on binfalse » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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:

1
2
3
4
> 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:

1
2
3
4
5
6
> # 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:

1
2
3
4
5
6
> # logical AND
> x&y
[1] FALSE  TRUE FALSE
> # logical OR
> x|y
[1]  TRUE  TRUE FALSE

Nice, isn’t it 😉

To leave a comment for the author, please follow the link and comment on their blog: binfalse » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.