PowerQuery Puzzle solved with R
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
#199–200
Puzzles
Author: ExcelBI
All files (xlsx with puzzle and R with solution) for each and every puzzle are available on my Github. Enjoy.
Puzzle #199
Data mining, maybe it is too big word for challenge we face today, but we need to dig up some information from given texts. Each of them have part number and order or delivery dates for each. Sometimes more than one. We need to extract them, clean if needed and sort by part and then by date. Little cleaning were needed so code is not as short as it could be. Check it.
Loading libraries and data
library(tidyverse) library(readxl) path = "Power Query/PQ_Challenge_199.xlsx" input = read_excel(path, range = "A1:A5") test = read_excel(path, range = "C1:D8")
Transformation
pattern_no = "\\d{3}" pattern_date = "\\d{1,2}/+\\d{1,2}/+\\d{2}" result = input %>% mutate(`Part No.` = str_extract_all(String, pattern_no), Date = str_extract_all(String, pattern_date)) %>% unnest(Date, `Part No.`) %>% mutate(Date = str_replace_all(Date, "//", "/")) %>% select(-String) %>% mutate(`Part No.` = as.numeric(`Part No.`), Date = as.POSIXct(Date, format = "%m/%d/%y", tz = "UTC")) %>% arrange(`Part No.`, Date)
Validation
identical(result, test) # [1] TRUE
Puzzle #200
What we have here today. Exam reports of 6 students on 4 exams in 2 parts. Not a perfect situation, because we all like data in one place in nice structure, we like them tidy. So we have to tidy them up. Fortunatelly it is not so hard as it can look. Find out yourself.
Loading libraries and data
library(tidyverse) library(readxl) path = "Power Query/PQ_Challenge_200.xlsx" input1 = read_excel(path, range = "A1:D6") input2 = read_excel(path, range = "F1:I6") test = read_excel(path, range = "A11:E17")
Transformation
in1 = input1 %>% pivot_longer(cols = -c(1), names_to = "subject", values_to = "score") in2 = input2 %>% pivot_longer(cols = -c(1), names_to = "subject", values_to = "score") result = bind_rows(in1, in2) %>% summarise(max = max(score), .by = c("subject", "Student")) %>% pivot_wider(names_from = "subject", values_from = "max") %>% arrange(Student) result = result %>% select(Student, sort(names(result)[2:5]))
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.
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.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.