Search code examples
rfunctionreshapedcast

How to reshape data in custom function with dcast?


I have big sales data.frame with many columns - my future parameters for function (status, payment, delivery, source etc).

week / item.type / source / order / payment / delivery
31 / device / desktop / 222-111 / cash / courier
32 / tariff / mobile / 222-333 / card / courier
33 / tariff / desktop / 111444 / cash / courier
34 / tariff /  mobile / 333-555 / card / pickup
35 / device / desktop / 343-222 / cash / pickup
36 / number / desktop / 123-223 / card / pickup

I need universal function to make mini tables in format week ~ source, week ~ delivery, week ~ payment for weekly report.

device
=============
week / 31 / 32 / 33 / 34 / 35 / 36
mobile / 134/ 234 / 536 / 345 / 345 / 333
desktop / 231/ 356 / 755 / 261 / 333 / 222

tariff
=============
week / 31 / 32 / 33 / 34 / 35 / 36
mobile / 11 / 24 / 64 / 27 / 13 / 89
desktop / 62 / 92 / 83 / 41 / 76 / 55

Dcast without function is working. Dplyr without dcast in function is wordking. Both in function - refused.

ord <- function(df, gds, x1p, x2p) {
  res <- filter(df, str_detect(item.type, gds)) %>%
    dplyr::group_by_(x1p, x2p) %>%
    dplyr::summarise(orders = n_distinct(order)) %>%
    reshape2::dcast(df, x1p ~ x2p, sum)
}

orders_src <- ord(df.raw, 'device', 'week', 'source')
orders_src <- ord(df.raw, 'tariff', 'week', 'source')

Help me, please.


Solution

  • As we are passing the arguments as strings, one option is group_by_at and also in the dcast, create the formula with paste

    ord <- function(df, gds, x1p, x2p) {
       filter(df, str_detect(item.type, gds)) %>%
         dplyr::group_by_at(vars(x1p, x2p)) %>%
         dplyr::summarise(orders = n_distinct(order)) %>%
         reshape2::dcast(., formula(paste(x1p,   x2p, sep= "~ ")),  sum)
      }