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.
#159–160
Puzzles
Author: ExcelBI
All files (xlsx with puzzle and R with solution) for each and every puzzle are available on my Github. Enjoy.
Puzzle #159
Today we have data about some salespeople. But they have only data about the months when they exceeded “norm” which is 100. Nonetheless those 100’s are also cost of employee so… We need to fill missing months with 100. Of course only those months that we know that person works. So again some time magic again
Load libraries and data
library(tidyverse) library(readxl) input = read_excel("Power Query/PQ_Challenge_159.xlsx", range = "A1:D19") test = read_excel("Power Query/PQ_Challenge_159.xlsx", range = "F1:I73")
Transformation
calendar = input %>% select(-c(Sales,Month)) %>% group_by(Name) %>% expand_grid(Y = unique(Year), M = 1:12) %>% distinct() %>% filter(Y == Year) %>% select(Name, Year, Month = M) %>% ungroup() result = calendar %>% left_join(input, by = c("Name", "Year", "Month")) %>% replace_na(list(Sales = 100))
Validation
identical(result, test) # [1] TRUE
Puzzle #160
Geography now! (It is a name of interesting YT channel.) But I really like Geo so, lets check it out. We have coordinates of several cities and our output should be distance matrix from each city to each city. I didn’t really check if coordinates are correct but it is not crucial to this task. Way of solving is crucial, because we need to use Pythagorean Theorem to find distnaces. Good luck!
Loading libraries and data
library(tidyverse) library(readxl) input = read_excel("Power Query/PQ_Challenge_160.xlsx", range = "A1:C8") test = read_excel("Power Query/PQ_Challenge_160.xlsx", range = "F1:M8")
Transformation
grid = crossing(city1 = input$Cities, city2 = input$Cities) %>% mutate(x1 = input$x[match(city1, input$Cities)], y1 = input$y[match(city1, input$Cities)], x2 = input$x[match(city2, input$Cities)], y2 = input$y[match(city2, input$Cities)], dist = round(sqrt((x2 - x1)^2 + (y2 - y1)^2),2)) %>% select(Cities = city1, city2, dist) %>% pivot_wider(names_from = city2, values_from = dist)
Validation
identical(test, grid) # [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.