Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

#211–212

### Puzzles

Author: ExcelBI

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

### Puzzle #211

Sometimes there is more than one team under your “jurisdiction” and you need to summarise data coming from different places. And we have it today. Most tricky part here is that we have multilevel header so we need to call specialist — unpivotr. When headers get simplified and data stacked into one proper data set, everything else is a piece of cake.

```library(tidyverse)
library(unpivotr)
library(janitor)

path = "Power Query/PQ_Challenge_211.xlsx"
input = read_xlsx(path, range = "A1:F10", col_names = FALSE)
test  = read_xlsx(path, range = "H1:J20")```

#### Transformation

```result = input %>%
as_cells() %>%
select(Group, chr, col, row) %>%
mutate(col = col %% 2 + 1) %>%
pivot_wider(names_from = col, values_from = chr) %>%
select(Group = 1, Row = 2, Name = 3, Income = 4) %>%
filter(!is.na(Name), Row != 2) %>%
mutate(Income = as.numeric(Income),
total_per_group = sum(Income),
Group = str_sub(Group, -1, -1),
.by = Group) %>%
arrange(desc(total_per_group), desc(Income), Name) %>%
select(Group, Name, Income)```

#### Validation

```identical(result, test)
# [1] TRUE```

### Puzzle #212

And again… People and cash, today we need to calculate commission for each salesperson involved in deals. This task need unpivoting one dataset, then join it to the other, and summarise some measures. To say shorter… everyday job. Check it out.

```library(tidyverse)

path = "Power Query/PQ_Challenge_212.xlsx"
T1 = read_excel(path, range = "A2:C7")
T2 = read_excel(path, range = "A11:E17")
test = read_excel(path, range = "H2:I7")```

#### Transformation

```input = T2 %>%
pivot_longer(cols = -c(1, 2), values_to = "Code") %>%
left_join(T1, by = "Code") %>%
na.omit() %>%
mutate(Amount = Sales * Commission) %>%
summarise(Amount = sum(Amount), .by = "Name") %>%
arrange(desc(Amount)) ```

#### Validation

```identical(input, test)
#> [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.