PowerQuery Puzzle solved with R

[This article was first published on Numbers around us - Medium, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

#147–148

Puzzles

Author: ExcelBI

All files (xlsx with puzzle and R with solution) for each and every puzzle are available on my Github. Enjoy.

Puzzle #147

Picture above showing sudoku-like puzzles looks difficult, but puzzle itself is really hardcore. Probably one of the toughests since I join this puzzle solving. We get table filled with data like unsolved sudoku (that is theme of image). We need to populate it with proper data filling sometimes up, sometimes down. Easier to say than to do. Just look on this spreadsheet. There are even empty rows to fill.

So lets check how I did it. I’ll try to explain my chain of thoughts while solving.

Load libraries and data

library(tidyverse)
library(readxl)

input = read_excel("Power Query/PQ_Challenge_147.xlsx", range = "A1:D17")
test  = read_excel("Power Query/PQ_Challenge_147.xlsx", range = "F1:I17") %>%
  janitor::clean_names()

Transformation

reshape <- function(input) {
  input %>%
    janitor::clean_names() %>%
    mutate(nr = row_number()) %>%
    # for each column enumerate not empty cells
    mutate(across(c(cust_id, cust_name, amount, type),
                  ~ ifelse(is.na(.), NA, cumsum(!is.na(.))),
                  .names = "index_{.col}"),
    # for each row find max index which will be used to find cust_id per row
           max_index = pmax(index_cust_id, index_cust_name, index_amount, index_type, na.rm = TRUE)) %>%
    group_by(max_index) %>%
    mutate(across(c(cust_id, cust_name, amount, type),
                  ~ max(., na.rm = TRUE)),
    # for each max_index get first and last row in which it occurs
           min_row = min(nr, na.rm = TRUE),
           max_row = max(nr, na.rm = TRUE)) %>%
    ungroup() %>%
    # remove originally empty rows
    filter(!is.na(max_index)) %>%
    select(-starts_with("index_"), -max_index, -nr) %>%
    distinct() %>%
    # using first and last row per index make sequence and unnest it to rows
    mutate(row_seq = map2(min_row, max_row, seq)) %>%
    unnest(row_seq) %>%
    select(-min_row, -max_row, -row_seq) %>%
    group_by(cust_id) %>%
    # final touch. add original row number to type
    mutate(type = paste0(type, row_number())) %>%
    ungroup()
}


result = reshape(input)

Validation

identical(result, test)
# [1] TRUE

Puzzle #148

After one hardcore, comes one pretty nice and easy to solve. And it is about fruits. What we get is column with strings containing names of fruits. We need to split them separately, count them and put in some kind of crosstab. Little bit weird because both rows and columns has the same dimension, name of fruit. Let go into.

Load libraries and data

library(tidyverse)
library(readxl)

input = read_excel("Power Query/PQ_Challenge_148.xlsx", range = "A1:A12")
test  = read_excel("Power Query/PQ_Challenge_148.xlsx", range = "C1:N12") 

Transformation

result = input %>%
  separate_rows(Fruits, sep = ", ") %>%
  mutate(Fruits = str_remove_all(Fruits, " ")) %>%
  group_by(Fruits) %>%
  summarise(Count = n()) %>%
  ungroup() %>%
  mutate(Fruits2 = Fruits) %>%
  pivot_wider(names_from = Fruits2, values_from = Count) 

Validation

all.equal(result, test)
#> [1] TRUE

# Today for the first time I used all.equal() instead of identical(). 
# Main reason is because if there are NAs, NA is not identical to NA,
# it return NA instead of TRUE. But NA is equal to NA, so final df is not
# identical, but it is equal to given answer.  
# In our eyes we can say they are the same. 

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.

To leave a comment for the author, please follow the link and comment on their blog: Numbers around us - Medium.

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.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)