Created
April 16, 2012 20:52
-
-
Save geofferyzh/2401435 to your computer and use it in GitHub Desktop.
RinAction - R Data Manipulation - Date Variable
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
############################################################## | |
## ------------ Date Values ------------- | |
## Dates are typically entered into R as character strings | |
## and then translated into date variables that are stored | |
## numerically | |
## | |
## Date format | |
## %d --> Day as a number (0-31) | |
## %a --> Abbreviated weekday (Mon, Tue, Fri) | |
## %A --> Unabbreviated weekday (Monday, Tuesday) | |
## %m --> Month (00-12) | |
## %b --> Abbreviated month (Jan, Feb, Mar) | |
## %B --> Unabbreviated month (January, Feburary) | |
## %y --> 2-digit year (07) | |
## %Y --> 4-digit year (2007) | |
############################################################## | |
########################################### | |
# Converting Characters to Date variables | |
########################################### | |
# Default date format is YYYY-MM-DD | |
mydates <- as.Date(c("2007-06-22", "2004-02-13")) | |
mydates | |
# Converting character values to dates using various format | |
strDates <- c("01/05/1965", "08/16/1975") | |
dates <- as.Date(strDates, "%m/%d/%Y") | |
dates | |
myformat <- "%m/%d/%y" | |
leadership$date | |
leadership$date <- as.Date(leadership$date, myformat) | |
########################################### | |
# Converting Date variables to Characters | |
########################################### | |
strDates <- as.character(dates) | |
strDates | |
###################### | |
#Useful date functions | |
###################### | |
Sys.Date() | |
date() | |
today <- Sys.Date() | |
format(today, format = "%B %d %Y") | |
format(today, format = "%A") | |
###################### | |
# Time Difference | |
###################### | |
# Method 1 | |
startdate <- as.Date("2004-02-13") | |
enddate <- as.Date("2009-06-22") | |
days <- enddate - startdate | |
# Method 2 - Using difftime() function | |
today <- Sys.Date() | |
dob <- as.Date("1956-10-10") | |
difftime(today, dob, units="days") | |
difftime(today, dob, units="week") | |
difftime(today, dob, units="mins") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment