Introduction to Business Analytics with R
Creating a Datetime Object in Base R
# Convert the character string into a date object using base R
# The format is specified as MM/DD/YYYY
d <- as.Date("05/08/2020", format = "%m/%d/%Y")
Checking the Data Type of the d Object
# Print the object to check if it is in date format
print(d)
## [1] "2020-05-08"
Installing and Loading the lubridate Package
# Install lubridate if not already installed
# install.packages("lubridate")
# Load the lubridate package
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
Extracting Year, Month, Week, and Weekday
# Extract year, month, week number, and weekday number from d
d_year <- year(d)
d_month <- month(d)
d_week <- week(d)
d_day <- wday(d)
# Display the extracted values
print(d_year)
## [1] 2020
print(d_month)
## [1] 5
print(d_week)
## [1] 19
print(d_day)
## [1] 6
Creating a New Date Object 25 Days Later
# Create a new date object that is 25 days after d
d_25 <- d + 25
# Display the new date object
d_25
## [1] "2020-06-02"
Calculating the Difference Between Dates
# Calculate the difference between d and d_25
diff_days <- difftime(d_25, d, units = "days")
# Display the difference
diff_days
## Time difference of 25 days