Skip to content

Instantly share code, notes, and snippets.

@romainfrancois
Created December 7, 2017 13:32
Show Gist options
  • Save romainfrancois/c9406cc7b9776706dd1c11269c0d1965 to your computer and use it in GitHub Desktop.
Save romainfrancois/c9406cc7b9776706dd1c11269c0d1965 to your computer and use it in GitHub Desktop.
library(purrr)
library(dplyr)
na_set <- function(x, p){
p <- as_mapper(p)
x[p(x)] <- NA
x
}
# or something like this using case_when
# na_set <- function(x, p){
# p <- as_mapper(p)
# na <- as(NA, typeof(x))
#
# case_when(
# p(x) ~ na,
# TRUE ~ x
# )
# }
# > a <- c(NA, letters[1:5] )
# > na_set(a, ~. == "a")
# [1] NA NA "b" "c" "d" "e"
napalm_all <- function(data, p){
mutate_all(data, funs(na_set(., p)) )
}
napalm_at <- function(data, at, p){
mutate_at(data, at, funs(na_set(., p)) )
}
napalm_if <- function(data, test, p){
mutate_if(data, test, funs(na_set(., p)) )
}
a <- c(NA, letters[1:5] )
na_set(a, ~. == "a")
small <- airquality %>%
slice(1:10)
# set NA in all columns when the variable is < 20
napalm_all( small, ~ . < 20 )
# set NA only for these variables, using the tidy select
# notation given for free by mutate_at
napalm_at( small, vars(Ozone:Wind), ~ . < 20 )
# same for the if variant, using mutate_if
napalm_if( small, is.numeric, ~ . < 20)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment