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

#213–214

### Puzzles

Author: ExcelBI

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

### Puzzle #213

Two warehouses gave us some summary, but products there are sometimes in packages, sometimes in batches. So we need to find out how many products and groups are in both warehouses. So we need to merge, split and pivot data, but in certain order. Find out how.

```library(tidyverse)
library(janitor)

path = "Power Query/PQ_Challenge_213.xlsx"

T1 = read_excel(path, range = "A2:C8")
T2 = read_excel(path, range = "A12:C16")

test = read_excel(path, range = "F2:K9")```

#### Transformation

```T_full = bind_rows(T1, T2) %>%
separate_rows(Item, sep = ", ") %>%
separate_rows(Group, sep = ", ") %>%
pivot_wider(names_from = Item, values_from = Stock, values_fn = sum) %>%

#### Validation

```all.equal(test, T_full, check.attributes = FALSE)
#> [1] TRUE```

### Puzzle #214

Sometimes we have to do transformation in exactly oposite direction. And today we have to split one table into three that are specific to one of three zoos. Fortunatelly pivoting is powerful and we can do some tricks in it.

```library(tidyverse)

path = "Power Query/PQ_Challenge_214.xlsx"
input = read_excel(path, range = "A1:C13")
test  = read_excel(path, range = "E1:J7")```

#### Transformation

```result = input %>%
arrange(Animals, .by = Zoo) %>%
mutate(nr = row_number(), .by = Zoo) %>%
pivot_wider(
names_from = Zoo,
values_from = c(Animals, Count),
names_glue = "{.value}_{Zoo}"
) %>%
select(contains("Zoo1"), contains("Zoo2"), contains("Zoo3"))

colnames(result) = colnames(test)```

#### Validation

```all.equal(result, 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.