Data
The list of calories of all items carried by the elves.
data_in_file <- here("DATA", "2022", "input_day_01.txt")
(calories_raw <- read_table(
data_in_file,
col_names = FALSE,
skip_empty_rows = FALSE,
show_col_types = FALSE
))
# A tibble: 2,240 × 1
X1
<dbl>
1 2991
2 13880
3 13279
4 1514
5 9507
6 NA
7 6544
8 9672
9 13044
10 4794
# ℹ 2,230 more rows
Each elf inputs the calories their carrying in column, separating their items from the previous ones by an empty line.
What an idea these elves had! I wonder which programming language they used?!
Separate elves
Each NA
means new elf.
calories_new <- calories_raw %>%
rename(calories = X1) %>%
mutate(is_na = is.na(calories)) %>%
mutate(which_elf = cumsum(is_na) + 1)
calories_new
# A tibble: 2,240 × 3
calories is_na which_elf
<dbl> <lgl> <dbl>
1 2991 FALSE 1
2 13880 FALSE 1
3 13279 FALSE 1
4 1514 FALSE 1
5 9507 FALSE 1
6 NA TRUE 2
7 6544 FALSE 2
8 9672 FALSE 2
9 13044 FALSE 2
10 4794 FALSE 2
# ℹ 2,230 more rows
Count calories
calories_new %>%
group_by(which_elf) %>%
summarise(sum_cal = sum(calories, na.rm = TRUE)) %>%
arrange(desc(sum_cal))
# A tibble: 245 × 2
which_elf sum_cal
<dbl> <dbl>
1 213 68467
2 234 68143
3 89 66810
4 34 66631
5 209 65461
6 199 64966
7 145 64176
8 140 63815
9 110 63338
10 150 63104
# ℹ 235 more rows
🥳 TADA!