Handling Dates in R using as.Date
Parag Verma
21st March, 2022
Introduction
In this blog we will look at function which are used to handle dates in R
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
dt_val<-"2015-04"
dt_val
[1] "2015-04"
The above date doesnt have the day value in it.We will add date 15(middle of the month for ease of understanding).
Step 2: Adding Date value to the string
dt_val2<-str_c(dt_val,"-15")
dt_val2
[1] "2015-04-15"
The dt_val2 is still a text value.It has to converted into date format using as.Date
Step 3: Converting into Date format
dt_val3<-as.Date(dt_val2,"%Y-%m-%d")
dt_val3
[1] "2015-04-15"
Lets check the class for dt_val3 variable
class(dt_val3)
[1] "Date"
Please note the usage of capital Y in the argument. Since the text contains year as YYYY(2015), therefor we use captial Y.If it was just 15(meaning 2015), then we would have used small y
Step 4: Adding days to the date
dt_val4<-dt_val3 + 20
dt_val4
[1] "2015-05-05"
Adding 20 days to 15th April 2015 becomes 5th May 2015
Parting Comments
In this blog we created a very simple example of how a string containing date can be converted into proper date value.We will look into slight modifications of how date is represented and ways to handle that in R
R Complete Guide
Python Complete Guide
https://www.aimlmadeeasy.com/2021/09/python-complete-guide.html
No comments:
Post a Comment