Introduction to Business Analytics with R

Marievee Santana

Monday, August 19, 2024

Date–first code chunk. This is to create a date object. (Step 3)

Use a code chunk to create a datetime object d from the following character string that represents May 8, 2020: “05/08/2020”.

The code chunk creates an object for the date string. It is then formatted so the numeric values can be read into different functions/codes.

d <- '05/08/2020'
d <- as.Date(d, format = '%m/%d/%y')

Check the class. Second code chunk. This is to print the date object.(Step 4)

Use a new code chunk to check the data type of the d object by printing it. If it is in a date format, then it will show up as “2020-05-08”.

The code chunk displays the type and the value of the object.

class(d)
## [1] "Date"
print(d)
## [1] "2020-05-08"

Call Lubridate package. Lubridate package already installed. This calls the package.(Step 5)

If necessary, install the lubridate package using the Package pane in RStudio. In a new code chunk, load the lubridate package.

The lubridate package provides functions that make calcuations of dates easier in R.

install.packages(“lubridate”) library(“lubridate”)

library(lubridate)
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union

Using Lubridate. Extracting the year, month, day and week number from the date. (Step 6)

In a new code chunk, use the appropriate functions from the lubridate package to extract the year, month number, week number and weekday number from the object d created above. Save them as objects name d_year, d_month, d_week, and d_day respectively. Include code to display each of the four objects.

The code chunk displays the value for the requested function of d. In addition, it creates a new object name for that value.

year(d)
## [1] 2020
month(d)
## [1] 5
week(d)
## [1] 19
wday(d)
## [1] 6
d_year <- year(d)
d_month <- month(d)
d_day<- day(d)
d_week <- isoweek(d)

Another Date Object. Creating a second date object that is 25 days later. (Step 7)

Use a new code chunk to create another datetime object, d_25, using the object d, where d_25 is the date 25 days from now. Include code to display d_25.

The code chunk creates an object that represents object d plus 25 days. This value is displayed using the print function

d_25 <- d + 25

print(d_25)
## [1] "2020-06-02"

Comparing the Two Date Objects. Comparing the two date objects to comfir they are 25 days apart. (Step 8)

Finally, use a new code chunk to calculate and display the difference between d and d_25 using the difftime function and check whether the difference is 25 days.

The difftime function displays the time difference of 25 days between object d and d_25.

difftime(d_25, d, units = 'days')
## Time difference of 25 days