---
# Ordering the Records Chronologically

We&rsquo;d like find the number of reports per year.

```{r}
library(scales)
dogs %>%
  arrange(report_date)
```
  
???

The dates were loaded as strings as well, but alphabetical order by date string is not the same as chronological order.

Lubridate!

```
library(scales)
dogs %>%
  mutate(report_date = dmy(report_date)) %>%
  mutate(report_year = year(report_date)) %>%
  group_by(report_year) %>%
  ggplot() +
  aes(x=report_year) +
  geom_bar() +
  scale_x_continuous(breaks = pretty_breaks())
```

---
# Working with Dates and Times

[Lubridate](https://lubridate.tidyverse.org/) manages the complexities of date-time values.

```{r include=FALSE, message=FALSE}
library(lubridate)
```

.pull-left[
We parse date-time strings using `ymd`, `mdy`, &hellip;
```{r}
ymd(c("20220107", 
      "2022 Jan 7", 
      "2022, January, 7th"))
```

Switching timezones
```{r}
with_tz(now(), "Asia/Bangkok")
```
]
.pull-right[
We manipulate date elements using `year()`, `month()`, &hellip;.
```{r}
t <- today()
year(t)
year(t) <- year(t) - 100
t
```
]

.footnote[See the Lubridate Cheat Sheet (in RStudio, choose *Help*&rarr;*Cheat Sheets*&rarr;*Browse CheatSheets* and search for &ldquo;Lubridate&rdquo;)]

???

Dates and times are more complicated that you may have thought.

- Does every year have 365 days? No, there are leap years.
- Does every day have 24 hours? No, there is daylight savings time.
- Does every minute have 60 seconds? No, leap seconds get added due to the Earth's slowing orbit.
- What's the right way to format a date? Who knows...

Reference: https://r4ds.had.co.nz/dates-and-times.html#introduction-10

---
# Ordering the Records by Categorical Values

.pull-left[
```{r factor, fig.show = "hide", warning = FALSE}
dogs %>%
  ggplot() +
  aes(x=handedness) +
  geom_bar()
```
]
.pull-right[
```{r ref.label = "factor", echo = FALSE, warning = FALSE, out.width = "100%", fig.width = 8}
```
]

???
Notice that handedness has been imported as a string.
Factors are a more efficient way to handle categorical data values.

Demo

1. Start by factorizing `handedness`: `mutate(handedness = factor(handedness))`
2. We don't want alphabetical ordering: `mutate(handedness = fct_infreq(handedness))`
3. Filter out the bad values: 
  - `filter(handedness %in% c("left", "right", "ambidextrous"))`

References

- https://forcats.tidyverse.org/
- https://mdsr-book.github.io/mdsr2e/ch-dataII.html#factors-or-strings

```
handedness_values <- c("left", "right", "ambidextrous")
dogs %>%
  mutate(
    handedness = 
      fct_infreq(
        case_when(
          handedness %in% handedness_values ~ handedness,
          TRUE ~ NA_character_
        )
      )
  ) %>%
  filter(!is.na(handedness)) %>%
  ggplot() +
  aes(x=handedness) +
  geom_bar()
```

