#227–228
Author: ExcelBI
All files (xlsx with puzzle and R with solution) for each and every puzzle are available on my Github. Enjoy.
We are given two tables one with employees data, and second with conditional assignment of salary. There is kind of regular expression in there but not in official notation, but rather giving asterisk power of Joker — replace one or many characters. As this placeholder notation cannot be used in R, I made some modification in T2 table using as I called it BRAIN.API (my own mind :D). Check what was later.
library(tidyverse) library(readxl) path = "Power Query/PQ_Challenge_227.xlsx" input1 = read_excel(path, range = "A2:D13") input2 = read_excel(path, range = "F2:H6") test = read_excel(path, range = "J2:N11") %>% arrange(Sequence, Name)
input2 = input2 %>% mutate(pattern_seq = c("^1.*", "321", ".*", ".*8$"), pattern_name = c("^M.*", "^S.*", ".*[aA]$", ".*")) input = input1 %>% cross_join(input2) %>% mutate(check_seq = str_detect(string = Sequence.x, pattern = pattern_seq), check_name = str_detect(string = Name.x, pattern = pattern_name), both_conditions = check_seq & check_name) %>% filter(both_conditions) %>% select(Sequence = Sequence.x,Name = Name.x, Weight, `Bonus %`, Salary) %>% arrange(Sequence, Name)
all.equal(input, test, check.attributes = FALSE) #> [1] TRUE
Sometimes tables need some stretching and squeezing… and some stretching again. Especially when there are more than one header available. Fortunatelly we have special package for such cases: unpivotr. We need to “behead” some columns and rows and then we would put it in order we all accept to follow.
library(tidyverse) library(readxl) library(unpivotr) path = "Power Query/PQ_Challenge_228.xlsx" input = read_excel(path, range = "A1:H5", col_names = F) test = read_excel(path, range = "J1:M20") %>% arrange(Category, Student, Value)
result = input %>% as_cells() %>% behead("left", "Student") %>% behead("up-left", "Category") %>% behead("up", "Value") %>% select(Student, Category, Value, Marks = chr) %>% mutate(Marks = as.integer(Marks)) %>% na.omit() %>% arrange(Category, Student, Value)
all.equal(result, test, check.attributes = F) #> [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.
PowerQuery Puzzle solved with R was originally published in Numbers around us on Medium, where people are continuing the conversation by highlighting and responding to this story.