#####Introduction to Business Analytics with R#####
In this section I am converting a date string into a date object of a standard format and then displaying it.
date1Words<- 'May 8, 2020'
d <- format(as.Date(date1Words, format = "%B %d, %Y"), "%m/%d/%Y")
d <- as.Date(d, format = '%m/%d/%y')
print(d)
## [1] "2020-05-08"
Now I check the datatype of the date object.
class(d)
## [1] "Date"
I already installed the lubridate package so I will load it.
library(lubridate)
## Warning: package 'lubridate' was built under R version 4.3.3
##
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
Let’s extract a few date elements from the d date object using the lubridate functions.I will display them in this chunk as well.
d_year = year(d)
d_month = month(d)
d_week = week(d)
d_day = wday(d)
print(c(d_year, d_month, d_week, d_day))
## [1] 2020 5 19 6
Create a new datetime object d_25 based on object d plus 25 days.The instructions for this section are ambiguous in saying, “..where d_25 is the date 25 days from now,” but d is a specific date, not today() or “now”. So I am picking the meaning I think is intended.
d_25 = d + 25
print(d_25)
## [1] "2020-06-02"
Finally, let’s check that thee difference between d and d_25 is actually 25 days.
diff <- difftime(d_25, d, units = "days")
print(diff)
## Time difference of 25 days
diff == 25
## [1] TRUE