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.
#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.
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.