Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

data.table with extended `==` function not working in R

This is a follow-up question below.

How to extend `==` behavior to vectors that include NAs?

In the link, suppose we would like to compare

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a = c(1,2,NA)
b = c(1,3,NA)

Using the function of "%==%" <- function(a, b) (!is.na(a) & !is.na(b) & a==b) | (is.na(a) & is.na(b)), and we have the following result

a %==% b
# TRUE FALSE  TRUE

My question is how to use %==% in the data.table::data.table function. Why the following code does not work properly? The first two results are good, but it seems that %==% cannot be used with operations, i.e. the a+a2 below.

dt_a = data.table(a = a, a2 = a+a)
dt_a[,a %==% b] 
# TRUE FALSE  TRUE
dt_a[,a2 %==% b]
# FALSE FALSE  TRUE
dt_a[,a+a2 %==% b]
# 1  2 NA # this line of result is confusing.

>Solution :

It’s a problem of operator precedence. You would need

dt_a[,(a+a2) %==% b]

The fake equals has a different precedence than a normal == what you write originally was equivalent to

dt_a[,a+(a2 %==% b)]

Addition operators are higher precedence than test for equality but lower precedence than custom infix %% functions. See the ?Syntax help page for the full details.

Note this doesn’t have anything to do with data.table specifically. Same things happens outside

a <- c(1,2,NA)
b <- c(1,3,NA)
a2 <- a+ a
a+a2 %==% b
# [1]  1  2 NA
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading