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.
#145–146
Puzzles
Author: ExcelBI
All files (xlsx with puzzle and R with solution) for each and every puzzle are available on my Github. Enjoy.
Puzzle #145
This time our task is to summarise sales from three stores, but there are strings attached. They shouldn’t be just added, but cummulativelly for store and year. But it would be to easy, we need to base year on date of first sale. So each store has it different here. We need to find year ranges for them and then summarise them separately. Let’s try.
Load libraries and data
library(tidyverse) library(readxl) input = read_excel("Power Query/PQ_Challenge_145.xlsx", range = "A1:C16") test = read_excel("Power Query/PQ_Challenge_145.xlsx", range = "F1:I16")
Transformation
result = input %>% group_by(Store) %>% mutate(min_date = min(Date), year = case_when( between(Date, min_date, min_date + years(1)) ~ 1, between(Date, min_date + years(1), min_date + years(2)) ~ 2, between(Date, min_date + years(2), min_date + years(3)) ~ 3, between(Date, min_date + years(3), min_date + years(4)) ~ 4, between(Date, min_date + years(4), min_date + years(5)) ~ 5 )) %>% ungroup() %>% group_by(Store, year) %>% mutate(Column1 = cumsum(Sale)) %>% ungroup() %>% select(-year, -min_date)
Validation
identical(result, test) #> [1] TRUE
Puzzle #146
In this puzzle we have data collected from three groups. It is possibly the sales value or ammount. But each group had certain threshold which they have to achieve. This threshold is depicted as the edge of rocky shelf of cliff. We have to find people that in each group are just below or just above threshold (and there can be more than one person who met conditons). Lets do it.
Load libraries and data
library(tidyverse) library(readxl) input = read_excel("Power Query/PQ_Challenge_146.xlsx", range = "A1:D14") test = read_excel("Power Query/PQ_Challenge_146.xlsx", range = "F1:I7")
Transformation
result = input %>% group_by(Group) %>% mutate(Category = ifelse(Value == Threshold, "Equal", ifelse(Value > Threshold, "High", "Low"))) %>% ungroup() %>% filter(Category != "Equal") %>% group_by(Group, Category) %>% mutate(valid = ifelse(Category == "High", min(Value), max(Value))) %>% ungroup() %>% filter(Value == valid) %>% select(-valid, -Category)
Validation
identical(result, test) # [1] TRUE
Thanks for your engagement, and let me know if you have any comments.
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.