funs icon indicating copy to clipboard operation
funs copied to clipboard

Implement na_if()

Open hadley opened this issue 5 years ago • 2 comments
trafficstars

Needs to be implemented in such a way that you can replace NaN values:

dplyr::na_if(c(NA, NaN, 1), 1)
#> [1]  NA NaN  NA

(from https://github.com/tidyverse/dplyr/issues/4627)

hadley avatar Dec 11 '19 22:12 hadley

We need to figure out the semantics — I think probably it should using matching not equality. And maybe it should only be vectorised in its first argument? Maybe it should just be this?

na_if <- function(x, na) {
 x[vec_in(x, na)] <- NA
 x
}

Which makes it a special case of case_in(): case_in(x, y ~ NA)

hadley avatar May 05 '21 13:05 hadley

Regarding na_if() being match-like, we document that na_if() is like SQL NULLIF(), and that uses equality. And a few people use it that way (after looking at GitHub). So it is probably best to leave it like this and promote some other way to do match-like replacement with NAs. See my full analysis in: https://github.com/tidyverse/dplyr/pull/6329#issue-1302637632

DavisVaughan avatar Jul 16 '22 20:07 DavisVaughan