PowerQuery Puzzle solved with R

Numbers around us
Numbers around us
Published in
3 min readJul 2, 2024

#195–196

Puzzles

Author: ExcelBI

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

Puzzle #195

Is it told that analysts spend big chunk of their time on cleaning data. And sometimes it is indeed a mess. We have list of orders made by people, with products, prices and amounts written “how they liked”. Sometimes concatenated by commas, colons and even ampersands. And we need to clean it up, check which vendor gave us each product, and finally get to know how much we need to pay for vendors. Let’s do it.

Loading libraries and data

library(tidyverse)
library(readxl)

path = "Power Query/PQ_Challenge_195.xlsx"
input1 = read_xlsx(path, range = "A1:C5")
input2 = read_xlsx(path, range = "A8:B11")
test = read_xlsx(path, range = "F1:G4")

Transformation

result1 = input1 %>%
mutate(across(everything(), ~str_split(.x, "\\W+"))) %>%
unnest(cols = everything()) %>%
mutate(total = as.numeric(`Unit Price`) * as.numeric(Quantity)) %>%
select(Items, total)

result2 = input2 %>%
mutate(across(everything(), ~str_split(.x, "\\W+"))) %>%
unnest(cols = everything()) %>%
mutate(part = n(), .by = Items)

result = result2 %>%
left_join(result1, by = "Items") %>%
mutate(paid_by_stockist = total/part) %>%
summarise(`Amount Paid` = sum(paid_by_stockist, na.rm = T), .by = Stockist)

Validation

identical(result, test)
# [1] TRUE

Puzzle #196

Sometimes there are documents that have to be done certain way, and there is no other possibility (I mean technically can be done, but obligation is obligation). And one of those in my experience is school class schedules and reports. And now we have something similar to both of them at once to transpose from nice table.

Loading libraries and data

library(tidyverse)
library(readxl)

path = "Power Query/PQ_Challenge_196.xlsx"
input = read_xlsx(path, range = "A1:C11")
test = read_xlsx(path, range = "F1:O5")

Transformation

result = input %>%
mutate(class1 = Class) %>%
pivot_wider(names_from = Subject, values_from = c(class1, Marks), names_sep = "-") %>%
select(-Class) %>%
rename_with(~str_remove(., "class1-"), starts_with("class1-")) %>%
select(sort(names(.), decreasing = FALSE)) %>%
select(1:3,9:10, everything())

Validation

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

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.