Import your data

babynames<- read_excel("../00_data/mydata2.xlsx")

# Top 15 male names
top15_male <- babynames %>%
  filter(sex == "M") %>%
  group_by(Name) %>%
  summarize(Proportion = sum(Proportion)) %>%
  arrange(desc(Proportion)) %>%
  slice_head(n = 15)

# Top 15 female names
top15_female <- babynames %>%
  filter(sex == "F") %>%
  group_by(Name) %>%
  summarize(Proportion = sum(Proportion)) %>%
  arrange(desc(Proportion)) %>%
  slice_head(n = 15)

Chapter 15

Create a factor

babynames %>% count(sex)
## # A tibble: 2 × 2
##   sex        n
##   <chr>  <int>
## 1 F     622425
## 2 M     426150
sex_levels <- c("F", "M")

data_rev <- babynames %>%
    mutate(sex = sex %>% factor(levels = sex_levels))

Modify factor order

Make two bar charts here - one before ordering another after

babynames_summary <- babynames %>%
  group_by(sex) %>%
  summarise(
    Count = mean(Count, na.rm = TRUE))

babynames_summary
## # A tibble: 2 × 2
##   sex   Count
##   <chr> <dbl>
## 1 F      196.
## 2 M      280.
ggplot(babynames_summary, aes(Count, sex)) + geom_point()

ggplot(babynames_summary, aes(Count, fct_reorder(sex, Count))) + geom_point()

Modify factor levels

Show examples of three functions:

  • fct_recode # Not applicaple for my data set

  • fct_collapse

babynames %>% 
    mutate(sex = fct_collapse(sex)) %>%
    count(sex)
## # A tibble: 2 × 2
##   sex        n
##   <fct>  <int>
## 1 F     622425
## 2 M     426150
  • fct_lump
babynames %>% 
    mutate(sex = fct_lump(sex)) %>%
    count(sex)
## # A tibble: 2 × 2
##   sex        n
##   <fct>  <int>
## 1 F     622425
## 2 Other 426150

Chapter 16

No need to do anything here.