```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE)
library(tidyverse) library(nycflights13) library(lubridate)
## Chapter 15
### Creating factors
```{r}
gss_cat
Unordered factor levels ```{r} # Transform data: calculate average tv hours by religion tvhours_by_religh <- gss_cat %>%
group_by(relig) %>%
summarise(
avg_tvhours = mean(tvhours, na.rm = TRUE)
)
tvhours_by_religh
tvhours_by_religh %>%
ggplot(aes(x = avg_tvhours, y = relig)) +
geom_point()
Ordered factor levels
```{r}
tvhours_by_religh %>%
ggplot(aes(x = avg_tvhours, y = fct_reorder(.f = relig, .x = avg_tvhours))) +
geom_point()+
#Labeling
labs(y = NULL, x = "Mean Daily Hours Watching TV")
Moving a single level to the front ```{r} tvhours_by_religh %>%
ggplot(aes(x = avg_tvhours,
y = fct_reorder(.f = relig, .x = avg_tvhours) %>%
fct_relevel("Don't Know"))) +
geom_point()+
#Labeling
labs(y = NULL, x = "Mean Daily Hours Watching TV")
```{r} gss_cat %>% distinct(race)
gss_cat %>%
# Rename levels
mutate(race_rev = fct_recode(race, "African American" = "Black")) %>%
select(race, race_rev) %>%
filter(race == "Black")
gss_cat %>%
mutate(race_col = fct_collapse(race, "Minority" = c("Black","Other"))) %>%
select(race, race_col) %>%
filter(race != "White")
gss_cat %>% count(race)
gss_cat %>% mutate(race_lump = fct_lump(race)) %>% distinct(race_lump)
## Ch16 Date and Times
### Creating date and times
```{r}
# From strings
"2022/10/28" %>% ymd()
#From numbers
20221028 %>% ymd()
"2022-10-28 4-41-30" %>% ymd_hms()