Import your data

data <- penguins

Chapter 15

Create a factor

data %>% count(island)
##      island   n
## 1    Biscoe 168
## 2     Dream 124
## 3 Torgersen  52
island_levels <- c("Biscoe", "Dream", "Torgersen")

data_rev <- data %>%
    mutate(island = island %>% factor(levels = island_levels))

Modify factor order

Make two bar charts here - one before ordering another after

data_summary <- data %>%
    group_by(island) %>%
    summarise(
    bill_len = mean(bill_len, na.rm = TRUE)
    )

data_summary
## # A tibble: 3 × 2
##   island    bill_len
##   <fct>        <dbl>
## 1 Biscoe        45.3
## 2 Dream         44.2
## 3 Torgersen     39.0
ggplot (data_summary, aes (bill_len, island)) + geom_point ()

ggplot (data_summary, aes (bill_len, fct_reorder (island, bill_len))) + geom_point()

Modify factor levels

Show examples of three functions:

  • fct_recode
data %>% 
    mutate(island = fct_recode(island,
                               "BiscoeIsland" = "Biscoe",
                               "DreamIsland" = "Dream",
                               "TorgersenIsland" = "Torgersen")) %>%
    count(island)
##            island   n
## 1    BiscoeIsland 168
## 2     DreamIsland 124
## 3 TorgersenIsland  52
  • fct_collapse
data %>%
    mutate(island = fct_collapse(island,
                                 BiscoeIsland = "Biscoe",
                                 Other = c("Dream", "Torgersen"))) %>%
    
    count(island)
##         island   n
## 1 BiscoeIsland 168
## 2        Other 176
  • fct_lump
data %>%
    mutate(island = fct_lump(island)) %>%
    count(island)
##   island   n
## 1 Biscoe 168
## 2  Dream 124
## 3  Other  52

Chapter 16

No need to do anything here.