Chapter 4 Notes

Harold Nelson

2023-02-06

Setup

library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.3.6      ✔ purrr   0.3.4 
## ✔ tibble  3.1.8      ✔ dplyr   1.0.10
## ✔ tidyr   1.2.1      ✔ stringr 1.4.1 
## ✔ readr   2.1.2      ✔ forcats 0.5.2 
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
library(lubridate)
## 
## Attaching package: 'lubridate'
## 
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union

Wondrous Functions: ymd, etc.

Task 1

Convert the string “3-1-2022” to a date assuming that the 3 is March.

Solution

the_date = mdy("3-1-2022")
print(the_date)
## [1] "2022-03-01"

Task 2

Convert the string “3-1-2022” to a date assuming that the 1 is January.

Solution

the_date = dmy("3-1-2022")
print(the_date)
## [1] "2022-01-03"

Task 3

Convert the string “2022.3.1” to a date assuming that the 3 is March.

Solution

the_date = ymd("2022.3.1")
print(the_date)
## [1] "2022-03-01"

Task 4

Convert the string “2022.3.1” to a date assuming that the 1 is January.

Solution

the_date = ydm("2022.3.1")
print(the_date)
## [1] "2022-01-03"

Task 5

Convert the string “January 3, 2022” to a date.

Solution

the_date = mdy("January 3, 2022")
print(the_date)
## [1] "2022-01-03"

Task 6

Convert the string “3 Jan 2022” to a date.

Solution

the_date = dmy("3 Jan 2022")
print(the_date)
## [1] "2022-01-03"

Stump the Chump

Try to find a reasonable way to express a date that lubridate can’t figure out.

Solution

the_date = mdy("jan 3 MCMLXX")
## Warning: All formats failed to parse. No formats found.
print(the_date)
## [1] NA

Task 7

Use make_date() to create a date in standard format given mo = 7; dy = 4; yr = 2023.

Solution

july_4 = make_date(2023,7,4)
july_4
## [1] "2023-07-04"
class(july_4)
## [1] "Date"

Output Formats

Review https://www.geeksforgeeks.org/how-to-use-date-formats-in-r/

Then create five different output versions of today’s date, which you can get from today().

Solution 1

today = today()
today
## [1] "2023-02-06"
today_pretty = format(today, "%m/%d/%y")
today_pretty
## [1] "02/06/23"

Solution 2

today_pretty = format(today, "%m/%d/%Y")
today_pretty
## [1] "02/06/2023"

Solution 3

today_pretty = format(today, "%m/%d/%Y")
today_pretty
## [1] "02/06/2023"

Solution 4

today_pretty = format(today, "%m/%d/%Y, %A")
today_pretty
## [1] "02/06/2023, Monday"

Solution 5

today_pretty = format(today, "%A, %B %d, %Y")
today_pretty
## [1] "Monday, February 06, 2023"