Last active
April 2, 2024 14:31
-
-
Save kdm9/fda8fd9c5c26edd9e685439ff2f8086b to your computer and use it in GitHub Desktop.
An `as.numeric()` in R that warns about non-numeric values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
as.numeric.verbose = function(x) { | |
# this code will parse german-style comma-as-decimal numbers or | |
# english-style dot-as-decimal numbers. | |
x = ifelse(grepl('^\\d+,\\d+$', x, perl=T), sub(',', '.', x, fixed=T), x) | |
x.num = as.numeric(x) | |
# Find which values got coerced to NA | |
coerced = which(!is.na(x) & is.na(x.num)) | |
if (length(coerced) > 0) { | |
cat("Following values coerced to NA:\n") | |
print(paste(coerced, x[coerced])) | |
} | |
x.num | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
whona = function(x, y) { | |
# Find which values got coerced to NA | |
coerced = which(!is.na(x) & is.na(y)) | |
if (length(coerced) > 0) { | |
cat("Following values coerced to NA:\n") | |
print(paste(coerced, x[coerced])) | |
} | |
y | |
} | |
truey_falsey = function(x) { | |
tf = dplyr::case_match(x, | |
c("1", "Y", "P", "Yes", "Present") ~ T, | |
c("0", "N", "A", "No", "Absent") ~F | |
) | |
return whona(x, tf) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment