Reputation: 199
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
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