Home > Software engineering >  can I do this without the slow rowwise() function in R?
can I do this without the slow rowwise() function in R?

Time:10-13

Shipping carriers (eg FedEx) define the length, width and height of boxes according to their relative lengths. The 'length' is always the longest side, followed by the 'depth' (they use w for weight so depth instead of width), and the 'height' is always the shortest side.

I'm currently doing this to rearrange the labels.

        select(products_id,
               products_weight,
               products_length,
               products_width,
               products_height) %>%
        rename(l = products_length,
               d = products_width,
               h = products_height) %>%
        rowwise() %>%
        mutate(ln = max(c(l, d, h)),
               dn = median(c(l, d, h)),
               hn = min(c(l, d, h))) %>%
        select(-l,-d,-h) %>%
        rename(
                l = ln,
                d = dn,
                h = hn,
                w = products_weight,
                sku = products_id
        )

Is there a faster way?

CodePudding user response:

I think this should work, but it's obviously untested with no sample data:

your_data %>% 
  select(
    sku = products_id,
    w = products_weight,
    pl = products_length,
    pw = products_width,
    ph = products_height
  ) %>%
  mutate(
    l = pmax(pl, pw, ph),
    h = pmin(pl, pw, ph),
    w = pl   pw   ph - l - h
  ) %>% 
  select(-pl, -pw, -ph)
  • Related