Skip to content

Instantly share code, notes, and snippets.

@drewgriffith15
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save drewgriffith15/f85dfe3b521cc99cae3c to your computer and use it in GitHub Desktop.

Select an option

Save drewgriffith15/f85dfe3b521cc99cae3c to your computer and use it in GitHub Desktop.
Handling Dates in R
# Sample dates
dates <- c("09/27/99", "03/15/08")
newDates <- as.Date(dates, format = "%m/%d/%y") # <-- Must change the format based on the format of what's being referenced
newDates # R output will be ISO standard dates in the format "%Y-%m-%d"
# Similar example to the last, but must be handled differently
dates <- c("09/27/1999", "03/15/2008")
newDates <- as.Date(dates, format = "%m/%d/%Y") # <-- the only difference here is the "Y" is capitalized
newDates # R output will be ISO standard dates in the format "%Y-%m-%d"
# Another example
dates <- c("Nov 7 1941", "Apr 16 2012")
newDates <- as.Date(dates, format = "%B %d %Y")
newDates
# from Excel
dates <- c(41567, 42001)
newDates <- as.Date(dates, origin = "1899-12-30")
newDates
# Now, change the default output of the new dates
format(newDates, "%a %b %d %Y")
# Just for fun...Build function to test if input year is a leap year
is_leap_year <- function(year){
if (year %% 400 == 0) {output = "TRUE"
}
else if (year %% 100 == 0) {output = "FALSE"
}
else if (year %% 4 == 0) {output = "TRUE"
}
else {output = "FALSE"
}
return(output)
}
# Return logical for current year
is_leap_year(as.numeric(format(Sys.time(),"%Y")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment