Kelsey
Kelsey

Reputation: 199

Use dplyr to change all values above threshold to NA

I have a data frame of numbers and I want to change all values over 8 to NA. I know there are other ways to do this, but I would like to accomplish this using dplyr so I can use a pipe with other code I have.

df <- data.frame(c(1:9), c(2:10))

This is what I've tried so far:

library(dplyr)

df %>%
  mutate(across(everything(), function(x) ifelse(x>8, NA, x)))

df %>%
  mutate(across(everything(), function(x) na_if(x >8)))

Upvotes: 1

Views: 1567

Answers (1)

akrun
akrun

Reputation: 887741

We can assign the output to the original object to make those changes as the %>% will not do the output printed on the console.

df <- df %>% 
       mutate(across(everything(), ~ ifelse(. > 8, NA, .)))

Or another option is %<>% operator from magrittr

library(magrittr)
df %<>%
    mutate(across(everything(), ~ ifelse(. > 8, NA, .)))

Upvotes: 2

Related Questions