Monday, March 21, 2022

Handling Dates in R using as.Date function

Handling Dates in R using as.Date


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

My Youtube Channel

No comments:

Post a Comment

Web Scraping Tutorial 4- Getting the busy information data from Popular time page from Google

Popular Times Popular Times In this blog we will try to scrape the ...