Import your data
library(tidyverse)
data <- read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/refs/heads/main/data/2022/2022-03-22/babynames.csv")
## Rows: 1924665 Columns: 5
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (2): sex, name
## dbl (3): year, n, prop
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
names(data)
## [1] "year" "sex" "name" "n" "prop"
data_small <- data %>%
select(year, sex, name, n) %>%
filter(name %in% c("James", "Mary"))
Separating and Uniting
babynames_sep <- data %>%
unite("year_sex", year, sex, sep = "_")
babynames_sep %>%
separate(
col = year_sex,
into = c("year", "sex"),
sep = "_"
)
## # A tibble: 1,924,665 × 5
## year sex name n prop
## <chr> <chr> <chr> <dbl> <dbl>
## 1 1880 F Mary 7065 0.0724
## 2 1880 F Anna 2604 0.0267
## 3 1880 F Emma 2003 0.0205
## 4 1880 F Elizabeth 1939 0.0199
## 5 1880 F Minnie 1746 0.0179
## 6 1880 F Margaret 1578 0.0162
## 7 1880 F Ida 1472 0.0151
## 8 1880 F Alice 1414 0.0145
## 9 1880 F Bertha 1320 0.0135
## 10 1880 F Sarah 1288 0.0132
## # ℹ 1,924,655 more rows
Separate a column
NA
Unite two columns
data %>%
unite(
col = "year_sex",
year,
sex,
sep = "_"
)
## # A tibble: 1,924,665 × 4
## year_sex name n prop
## <chr> <chr> <dbl> <dbl>
## 1 1880_F Mary 7065 0.0724
## 2 1880_F Anna 2604 0.0267
## 3 1880_F Emma 2003 0.0205
## 4 1880_F Elizabeth 1939 0.0199
## 5 1880_F Minnie 1746 0.0179
## 6 1880_F Margaret 1578 0.0162
## 7 1880_F Ida 1472 0.0151
## 8 1880_F Alice 1414 0.0145
## 9 1880_F Bertha 1320 0.0135
## 10 1880_F Sarah 1288 0.0132
## # ℹ 1,924,655 more rows
Missing Values
babynames_na <- data %>%
mutate(
n = ifelse(n < 10, NA, n)
)