O'Reilly logo

R Data Analysis Cookbook - Second Edition by Kuntal Ganguly

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Perform addition and subtraction of days from date objects:
> dt <- as.Date("1/1/2001", format = "%m/%d/%Y") 
> dt 
[1] "2001-01-01" 
 
> dt + 100                 # Date 100 days from dt
[1] "2001-04-11" 
 
> dt + 31 
[1] "2001-02-01"
  1. Subtract date objects to find the number of days between two dates:
> dt1 <- as.Date("1/1/2001", format = "%m/%d/%Y") 
> dt2 <- as.Date("2/1/2001", format = "%m/%d/%Y") 
> dt1-dt1 
 
Time difference of 0 days  
> dt2-dt1 
 
Time difference of 31 days 
> dt1-dt2 
 
Time difference of -31 days 
> as.numeric(dt2-dt1) 
[1] 31 
  1. Compare the date objects:
> dt2 > dt1 
[1] TRUE 
 
> dt2 == dt1 
[1] FALSE 
  1. Create date sequences:
> d1 <- as.Date("1980/1/1") > d2 <- as.Date("1982/1/1") > # Specify start date, end date and interval > seq(d1, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required