#225–226
Author: ExcelBI
All files (xlsx with puzzle and R with solution) for each and every puzzle are available on my Github. Enjoy.
Sometimes we have nice tables with so called tidy data, where each observation mean one row. But this can cause creating vast areas of data in spreadsheet, that are hard to find and interpret. That is why sometimes we need to fold data, squeeze them and so on to make maybe not tidy, but readable form like foldable map. In PQ Challenges we usually transform tables back and forth, and today we are squeezing and folding them.
library(tidyverse) library(readxl) path = "Power Query/PQ_Challenge_225.xlsx" input = read_excel(path, range = "A1:D9") test = read_excel(path, range = "F1:G12")
r1 = input %>% mutate(Id = consecutive_id(Group), `Emp ID` = as.character(`Emp ID`), Group = ifelse(Group == "Group A", "GroupA", Group)) r1_1 = r1 %>% select(Column1 = 1, Column2 = 2, ID = 5) r1_2 = r1 %>% select(Column1 = 4, Column2 = 3, ID = 5) r2 = rbind(r1_2, r1_1) %>% arrange(ID) %>% distinct() %>% select(-ID)
all.equal(r2, test, check.attributes = FALSE) #> [1] TRUE
As I wrote few lines before, sometimes we have chart with data that is sometimes even redundant to itself. And we need to press them like fresh lemon to get valuable information. Check this one as well.
library(tidyverse) library(readxl) path = "Power Query/PQ_Challenge_226.xlsx" input = read_excel(path, range = "A1:D13") test = read_excel(path, range = "F1:I19")
result = input %>% fill(`Dept ID`) %>% select(-`Highest Paid Employee`) %>% pivot_longer(-`Dept ID`, values_to = "Value") %>% separate(Value, into = c("Emp Names", "Salary", "Promotion Date"), sep = "-") %>% select(-name) %>% filter(!is.na(`Emp Names`)) %>% arrange(`Dept ID`, `Emp Names`) %>% mutate(`Promotion Date` = as.POSIXct(`Promotion Date`, format = "%m/%d/%Y", tz = "UTC"), Salary = as.numeric(Salary)) %>% select(`Dept ID`, `Emp Names`, `Promotion Date`, Salary)
all.equal(result, test, check.attributes = FALSE) #> [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.