Skip to content

Instantly share code, notes, and snippets.

@ClaytonJY
Last active July 3, 2018 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ClaytonJY/75bd13a2d741a08fbc6d9ab497a08d91 to your computer and use it in GitHub Desktop.
Save ClaytonJY/75bd13a2d741a08fbc6d9ab497a08d91 to your computer and use it in GitHub Desktop.
Replacing different values with missing in a subset of columns
library(tidyverse)
mt_tbl <- as_tibble(mtcars)
# types need to match those in mtcars (all doubles)
# careful; `na_if` doesn't work with multiple values
missing_codes <- list(
cyl = 6.0,
disp = 160.0,
carb = 1.0
)
# no iteration; baseline result
result_naive <- mt_tbl %>%
mutate(
cyl = na_if(cyl, missing_codes$cyl),
disp = na_if(disp, missing_codes$disp),
carb = na_if(carb, missing_codes$carb)
)
result_naive
# for loop
result_forloop <- mt_tbl
for (col in names(missing_codes)) {
result_forloop[[col]] <- na_if(result_forloop[[col]], missing_codes[[col]])
}
all_equal(result_naive, result_forloop)
# functional-ish
result_functionalish <- mt_tbl
result_functionalish[names(missing_codes)] <- imap(
result_functionalish[names(missing_codes)],
~ na_if(.x, missing_codes[[.y]])
)
all_equal(result_functionalish, result_naive)
# more functional, maybe
helper <- function(col, name, lookup) {
if (name %in% names(lookup)) {
col <- na_if(col, lookup[[name]])
}
col
}
result_functional <- imap_dfc(mt_tbl, helper, missing_codes)
all_equal(result_functional, result_naive)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment