I have a list of stores and I have a product (apples). I ran a system of linear equations to get the column \'var\'; this value represents the amount of apples you will
Here's a tidyverse solution. It relies on there being a net zero of each sku.
If that's the case, then we should be able to line up all the donated items (one row for each unit in the negative var
s, sorted by sku) with all the received items (one row for each positive var
, sorted by sku).
Consequently, the first 5 donated apples are matched with the first 5 received apples, and so on.
Then we total up the total for each sku between each donor and recipient pair and spread so each recipient gets a column.
complete
to match OP solutionlibrary(tidyverse)
output <- bind_cols(
# Donors, for whom var is negative
df %>% filter(var < 0) %>% uncount(-var) %>% select(-var) %>%
arrange(sku) %>% rename(donor = store),
# Recipients, for whom var is positive
df %>% filter(var > 0) %>% uncount(var) %>%
arrange(sku) %>% rename(recipient = store)) %>%
# Summarize and spread by column
count(donor, recipient, sku) %>%
complete(donor, recipient, sku, fill = list(n = 0)) %>%
mutate(recipient = paste0("ship_to_", recipient)) %>%
spread(recipient, n, fill = 0)
> output
# A tibble: 6 x 8
donor sku ship_to_a ship_to_b ship_to_c ship_to_d ship_to_e ship_to_f
1 a apple 0 0 0 0 0 0
2 b apple 0 0 0 0 0 0
3 c apple 1 4 0 0 1 0
4 d apple 0 0 0 0 1 0
5 e apple 0 0 0 0 0 0
6 f apple 0 0 0 0 3 0