Fill contingency table based on total variable

后端 未结 3 810
忘了有多久
忘了有多久 2021-01-23 03:07

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

3条回答
  •  一整个雨季
    2021-01-23 03:52

    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 vars, 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.

    Edit: corrected sign and added complete to match OP solution

    library(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
    

提交回复
热议问题