R’s Tricky == Operator, or "It depends on what the meaning of the word ‘is’ is"

February 11, 2015

(This article was first published on You Know, and kindly contributed to R-bloggers)

One scenario where R can trip up a programmer is when using the == operator or its relatives. The help page notes that “NA values are regarded as non-comparable”, which introduces some potentially unexpected behavior.

As a toy example, look what happens when trying to subset on a column that includes NA values.

df <- data.frame(a=11:15,b=c(3,NA,4,4,NA))




In each case, rows with an NA in the b column are returned. This might be surprising and not obvious if wrapped inside of a an aggregation such as nrow or sum. A safer way to accomplish this subsetting is by using the %in% operator. Like so:

df[df$b %in% 4,]

To leave a comment for the author, please follow the link and comment on their blog: You Know.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)