Handling Dates in R using as.Date Part 2
Parag Verma
25th March, 2022
Introduction
In this blog we will look at some more variations of date string and how they can be handled in R using as.Date function.The important thing to note here is that the date string should have all year, month and date components to leverage as.Date function.If they are not present, then we add/concatenate them to the string
package.name<-c("dplyr","stringr")
for(i in package.name){
if(!require(i,character.only = T)){
install.packages(i)
}
library(i,character.only = T)
}
Step 1: Creating dummy date vector
dt_val<-c("2015-4","2015-11","2015","04-30-15")
dt_val
[1] "2015-4" "2015-11" "2015" "04-30-15"
Step 2: Converting into Date format
For any date string to be converted into a date, it has to have year, month and date information.If the date string doesnt have these, then we add based on the following rules:
Rules:
- If there is no date information available, then we add 15(middle of the month) to the string
- If there is no month information available, then we add 06(middle of the year) to the string
- If there is no month and date information available, then we add 06(middle of the year) and 15(middle of the month)to the string
Step 3: Converting a date with just year and date information available
dt_val[1]
[1] "2015-4"
Adding June month to the date
dt_val1<-str_c(dt_val[1],"-06")
dt_val1
[1] "2015-4-06"
year_date_only<-as.Date(dt_val1,"%Y-%d-%m")
year_date_only
[1] "2015-06-04"
The above date represents 4th July 2015
Step 4: Converting a date with just year and month information available
dt_val[2]
[1] "2015-11"
Adding 15 as date
dt_val2<-str_c(dt_val[2],"-15")
dt_val2
[1] "2015-11-15"
year_month_only<-as.Date(dt_val2,"%Y-%m-%d")
year_month_only
[1] "2015-11-15"
The above date represents 15th Nov 2015
Step 5: Converting a date with just year information available
dt_val[3]
[1] "2015"
Adding 06 as the month and 15 as the date
dt_val3<-str_c(dt_val[3],"-06-15")
dt_val3
[1] "2015-06-15"
year_only<-as.Date(dt_val3,"%Y-%m-%d")
year_only
[1] "2015-06-15"
The above date represents 15th June 2015
Step 6: Converting a date with just month,date and year information available but year has only last two digits
dt_val[4]
[1] "04-30-15"
dt_val4<-dt_val[4]
dt_val4
[1] "04-30-15"
yy_available<-as.Date(dt_val4,"%m-%d-%y")
yy_available
[1] "2015-04-30"
The above date represents 30th April 2015
Parting Comments
In this blog we looked at some popular date strings that are available from imported excel and how they can be converted into a date format using as.Date function.
R Complete Guide
Python Complete Guide
https://www.aimlmadeeasy.com/2021/09/python-complete-guide.html