Showing posts with label Rstdio. Show all posts
Showing posts with label Rstdio. Show all posts

Wednesday, April 6, 2022

Add days to a Date and Subtract two dates in R

Add days to a date and subtract two dates in R


Introduction

In this blog we will look at the following:

  • Add days to a date string
  • Subtract two dates


package.name<-c("dplyr","stringr","lubridate")

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-04-30","2015-05-31")
dt_val
[1] "2015-04-30" "2015-05-31"


Step 2: Converting into Date format

The above two dates might look like they are in date format but they are string.If we do class of dt_val, we will get character.

class(dt_val)
[1] "character"

Hence before we can do any date related operation, we have to convert it into proper 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


dt_val_dates<-as.Date(dt_val,"%Y-%m-%d")
dt_val_dates
[1] "2015-04-30" "2015-05-31"

If we do class of dt_val_dates, we will get Date

class(dt_val_dates)
[1] "Date"


Step 3: Adding days to the date

Lets add 5 days to both the dates

dt_val_dates + 5
[1] "2015-05-05" "2015-06-05"

We can see that 5 days are successfully added to the dates


Step 4: Subtracting the two dates

dt_val_dates[2]
[1] "2015-05-31"


dt_val_dates[1]
[1] "2015-04-30"


If we subtract the two dates, then the difference in days should be 31.

dt_val_dates[2] - dt_val_dates[1]
Time difference of 31 days

We can see that the two dates have been successfully subtracted


Parting Comments

In this blog we looked at how we can leverage add days to a date and subtract two dates in R

My Youtube Channel

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 ...