data science tutorials and snippets prepared by tomis9
it’s an R package that makes working with dates easy;
because in basic, no-frills R working with dates may be a little bit daunting
Load the package
library(lubridate)
Convert a string to class Date
:
# the base way
d <- as.Date("2017-03-03")
class(d)
## [1] "Date"
# the lubridate way
d <- ymd("2017-03-03")
class(d)
## [1] "Date"
Extract year, month and day
year(d)
## [1] 2017
month(d)
## [1] 3
day(d)
## [1] 3
You can also modify the date on the fly:
year(d) <- 1410
month(d) <- 7
day(d) <- 15
print(d)
## [1] "1410-07-15"
class(d)
## [1] "Date"
Now, analogical to python’s datetime.now()
:
# the base way
n <- Sys.time()
# the lubridate way
n <- now()
## Warning in system("timedatectl", intern = TRUE): running command
## 'timedatectl' had status 1
Extracting hour, minute and second
hour(n)
## [1] 22
minute(n)
## [1] 54
second(n)
## [1] 37.01118
Days of the week
wday(d) # numbering starts from Sunday! you can adjust it, read ?wday
## [1] 1
Adding / subtracting dates:
print(d)
## [1] "1410-07-15"
d + years(1) # yearS - plural form
## [1] "1411-07-15"
d - months(2)
## [1] "1410-05-15"