【问题标题】:Inventory Management Calculation on RR上的库存管理计算
【发布时间】:2018-06-06 09:52:04
【问题描述】:

如何计算 R 上的库存数据投影?

假设我有库存数据:

Date, Product, Inventory
1-Jan-2017, A, 30
1-Jan-2017, B, 20
1-Jan-2017, C, 10

以及销售数据:

Date, Product, Sales
1-Feb-2017, A, 10
1-Feb-2017, B, 5
1-Mar-2017, A, 3

...(到 2017 年底)

以及购买数据

Date, Product, QtyPurchased
1-Feb-2017, A, 20
1-Feb-2017, B, 10
1-Feb-2017, C, 5

如何在 R 上生成新的(预测库存快照)数据框,使数据框看起来像 ():

Date, Product, Inventory
1-Jan-2017, A, 30
1-Feb-2017, A, 30+20-10 = 40
...
1-Jan-2017, B, 20
1-Feb-2017, B, 20-5+10 = 15

(计算是为了解释数字“15”和“40”背后的逻辑。它们不应该打印在数据框中)

只要计算正确,数据排列无所谓。

在 Excel 上,它将使用 VLOOKUP 并指向不同的单元格位置(例如,向左/向右移动 1 个单元格以获取下个月的值)。

但是我如何在 R 上做到这一点?

【问题讨论】:

    标签: r datetime


    【解决方案1】:

    我们先合并数据集。

    library(tidyverse)
    dat <- full_join(inventory, sales)
    dat <- full_join(dat, purchase)
    

    我们还将Sales 替换为它们的负值。然后我们转换日期并将 NA 替换为 0。

    dat2 <- dat %>%
      mutate(Sales = -Sales) %>%
      gather(transaction, value, -Date, -Product) %>%
      mutate(Date = as.Date(Date, format = "%d-%B-%Y")) %>%
      arrange(Date) %>%
      mutate(value = replace_na(value, 0))
    

    现在transaction的等级排列方式是QtyPurchased在每个日期排在最后,我们可以得到value按日期的累计和,得到QtyPurchased对应的值(使用dplyr::last函数)。

    dat2 %>%
      group_by(Product) %>%
      mutate(value = cumsum(value)) %>%
      ungroup() %>%
      group_by(Date, Product) %>%
      summarise(value = last(value)) %>%
      arrange(Product)
    
    # # A tibble: 7 x 3
    # # Groups:   Date [3]
    #   Date       Product value
    #   <date>     <chr>   <dbl>
    # 1 2017-01-01 A          30
    # 2 2017-02-01 A          40
    # 3 2017-03-01 A          37
    # 4 2017-01-01 B          20
    # 5 2017-02-01 B          25
    # 6 2017-01-01 C          10
    # 7 2017-02-01 C          15
    

    数据

    inventory <- read.table(text = "Date, Product, Inventory
    1-Jan-2017, A, 30
    1-Jan-2017, B, 20
    1-Jan-2017, C, 10", header = T, sep = ",", stringsAsFactors = F, strip.white = T)
    inventory
    
    sales <- read.table(text = "Date, Product, Sales
    1-Feb-2017, A, 10
    1-Feb-2017, B, 5
    1-Mar-2017, A, 3", header = T, sep = ",", stringsAsFactors = F, strip.white = T)
    
    purchase <- read.table(text = "Date, Product, QtyPurchased
    1-Feb-2017, A, 20
    1-Feb-2017, B, 10
    1-Feb-2017, C, 5", header = T, sep = ",", stringsAsFactors = F, strip.white = T)
    

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多