#145–146
Author: ExcelBI
All files (xlsx with puzzle and R with solution) for each and every puzzle are available on my Github. Enjoy.
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.
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")
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)
identical(result, test) #> [1] TRUE
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.
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")
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)
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.