Replace some values by NA

I have a variable that I want to replace some values by NA. Here's a quick example

x <- 1:15

Let's say I want everything that is above 10 to be NAs. In other words, I want x to be something like this:

1 2 3 4 5 6 7 8 9 10 NA NA NA NA NA

Is there a way to do this with tidyverse (or what is the best way to do this)? I tried na_if but that doesn't work if the condition is a range (it seems to take only a certain value). Using case_when doesn't work either. Any thoughts? Thanks!

Hi @Normal_distribution.

This should work:

dplyr::if_else(x > 10, NA_integer_, x)
1 Like

Terrific! Thank you so much! Never used NA_*_ before so this is totally new to me. Quick follow-up: if I have a vector of double, can I just use NA_real_ instead of NA_integer_? My guess is yes, but I want to double check to make sure things don't have unexpected behaviors

?stringr::str_replace_na

...if I have a vector of double, can I just use NA_real_ instead of NA_integer_?

Yes, this is correct!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.