Last active
May 25, 2021 11:40
-
-
Save micstr/69a64fbd0f5635094a53 to your computer and use it in GitHub Desktop.
Testing dates in R - an IsDate() function
This file contains hidden or 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
# Trying to find a basic test for dates in R. was looking for a is.Date like as.Date vibe | |
IsDate <- function(mydate, date.format = "%d/%m/%y") { | |
# Check if field is a date using as.Date that looks for unambiguous dates | |
# Assumes date format so NA returned not Character error. | |
# Why? with no date format, R tries two defaults then gives error. | |
# BUT With a dateformat R returns NA | |
# Args | |
# Suspected date and optional date format string | |
# Returns | |
# TRUE if thinbks it is a date | |
tryCatch(!is.na(as.Date(mydate, date.format)), | |
error = function(err) {FALSE}) | |
} | |
mydate <- "price" | |
IsDate(mydate) | |
# FALSE | |
mydate <- "1/3/2015" | |
IsDate(mydate) | |
# TRUE | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If I see it right, this cannot handle e.g. NAs. I instead suggest using
which leads to a
TRUE/FALSE
result:Created on 2021-05-25 by the reprex package (v2.0.0)