PowerQuery Puzzle solved with R

Numbers around us
Numbers around us
Published in
3 min readSep 24, 2024

#219–220

Puzzles

Author: ExcelBI

All files (xlsx with puzzle and R with solution) for each and every puzzle are available on my Github. Enjoy.

Puzzle #219

Somebody make request for equipment for new employees. But we have little mess here, if two devices with the same OS is needed it looks, like D1, D2 — OS1, and if we have two devices of the same type but on different OS it will look like D1 — OS1, OS2. There is no easy way just to separate them. But it is not impossible, check it.

Loading libraries and data

library(tidyverse)
library(readxl)

path = "Power Query/PQ_Challenge_219.xlsx"
input = read_excel(path, range = "A1:B7")
test = read_excel(path, range = "D1:F12")

Transformation

devices = c("Laptop", "Desktop", "Mobile")

result = input %>%
separate_rows(Machine, sep = ", ") %>%
separate(Machine, into = c("Device", "OS"), sep = " - ",remove = FALSE) %>%
mutate(OS = case_when(
is.na(OS) & Device %in% devices ~ lead(OS,1),
is.na(OS) & !Device %in% devices ~ Device,
TRUE ~ OS),
Device = case_when(
!Device %in% devices ~ lag(Device,1),
TRUE ~ Device)) %>%
select(-Machine)

Validation

identical(result, test)
#> [1] TRUE

Puzzle #220

And once again we have puzzle based on project management. We have list of activities, but we need to find a way to see it all in context of months. Some table transformation is needed to achieve it, so let us start it.

Load libraries and data

library(tidyverse)
library(readxl)

path = "Power Query/PQ_Challenge_220.xlsx"
input = read_excel(path, range = "A1:D9")
test = read_excel(path, range = "A13:I18") %>% replace(is.na(.), "")

Transformation

result = input %>%
mutate(Start = floor_date(Start, "month"),
Finish = floor_date(Finish, "month")) %>%
mutate(seq = map2(Start, Finish, seq, by = "month")) %>%
unnest(seq) %>%
select(-Start, -Finish) %>%
mutate(rn = row_number(), .by = c("Project", "seq")) %>%
pivot_wider(names_from = seq, values_from = Activities, values_fill = "") %>%
select(-rn)

names(result) = names(test)

Validation

result == test
# two cells in wrong order.

Feel free to comment, share and contact me with advices, questions and your ideas how to improve anything. Contact me on Linkedin if you wish as well.

--

--

Numbers around us
Numbers around us

Self developed analyst. BI Developer, R programmer. Delivers what you need, not what you asked for.