我正在嘗試確定對縮進的物料清單 (BOM) 進行預測所需的數量,以進行一些庫存控制。BOM 對子裝配有多個級別,因此父項所需的數量需要乘以每個級別。例如:
| 物品 | 等級 | 數量.每 | 父項 | 父數量預測 | 需要數量 |
|---|---|---|---|---|---|
| 成品 | 0 | 1 | 成品 | 10 | (1x10) = 10 |
| 子組件 1 | 1 | 2 | 成品 | 10 | (1x2x10)=20 |
| 組件 1 子組件 1 | 2 | 5 | 成品 | 10 | (1 x 2 x 5 x 10) = 100 |
| 子組件 2 | 1 | 4 | 成品 | 10 | (1 x 4 x 10) = 40 |
| 組件 1 子組件 2 | 2 | 2 | 成品 | 10 | (1 x 4 x 2 x 10) = 80 |
| 組件 1 組件 1 子組件 2 | 3 | 2 | 成品 | 10 | (1 x 4 x 2 x 2 x 10) = 160 |
有沒有辦法通過將頂層數量引入到成品中來計算 R 中每行 BOM 所需的數量?
uj5u.com熱心網友回復:
預先:這是脆弱的:如果行順序發生變化,它會破壞......靜默。如果您有更好的方法來識別組和子組,最好使用它們。
但是,試試這個
dplyr
library(dplyr)
dat %>%
group_by(Parent.Item) %>%
group_by(L1 = cumsum(Level == 1), .add = TRUE) %>%
mutate(
Qty = Parent.Qty.Forecast * sapply(Level, \(lvl) prod(Quantity.Per[Level <= lvl]))
) %>%
ungroup()
# # A tibble: 6 x 7
# Item Level Quantity.Per Parent.Item Parent.Qty.Forecast L1 Qty
# <chr> <int> <int> <chr> <int> <int> <dbl>
# 1 Finished Item 0 1 Finished Item 10 0 10
# 2 Subassembly 1 1 2 Finished Item 10 1 20
# 3 Component 1 Subassembly 1 2 5 Finished Item 10 1 100
# 4 Subassembly 2 1 4 Finished Item 10 2 40
# 5 Component 1 Subassembly 2 2 2 Finished Item 10 2 80
# 6 Component 1 Component 1 Subassembly 2 3 2 Finished Item 10 2 160
基數R
dat$L1 <- with(dat, ave(Level == 1, Parent.Item, FUN = cumsum))
dat$Qty <- with(dat, ave(seq_len(nrow(dat)), list(Parent.Item, L1), FUN = \(rn) {
Parent.Qty.Forecast[rn] * sapply(Level[rn], \(lvl) prod(Quantity.Per[rn][Level[rn] <= lvl]))
}))
資料表
library(data.table)
# should use setDT(dat) instead
as.data.table(dat
)[, L1 := cumsum(Level == 1), by = .(Parent.Item)
][, Qty := Parent.Qty.Forecast * sapply(Level, \(lvl) prod(Quantity.Per[Level <= lvl])),
by = .(Parent.Item, L1) ]
資料
### without 'Qty.Needed'
dat <- structure(list(Item = c("Finished Item", "Subassembly 1", "Component 1 Subassembly 1", "Subassembly 2", "Component 1 Subassembly 2", "Component 1 Component 1 Subassembly 2"), Level = c(0L, 1L, 2L, 1L, 2L, 3L), Quantity.Per = c(1L, 2L, 5L, 4L, 2L, 2L), Parent.Item = c("Finished Item", "Finished Item", "Finished Item", "Finished Item", "Finished Item", "Finished Item"), Parent.Qty.Forecast = c(10L, 10L, 10L, 10L, 10L, 10L)), row.names = c(NA, -6L), class = "data.frame")
### with 'Qty.Needed`
dat <- structure(list(Item = c("Finished Item", "Subassembly 1", "Component 1 Subassembly 1", "Subassembly 2", "Component 1 Subassembly 2", "Component 1 Component 1 Subassembly 2"), Level = c(0L, 1L, 2L, 1L, 2L, 3L), Quantity.Per = c(1L, 2L, 5L, 4L, 2L, 2L), Parent.Item = c("Finished Item", "Finished Item", "Finished Item", "Finished Item", "Finished Item", "Finished Item"), Parent.Qty.Forecast = c(10L, 10L, 10L, 10L, 10L, 10L), Qty.Needed = c("(1x10) = 10", "(1x2x10)=20", "(1 x 2 x 5 x 10) = 100", "(1 x 4 x 10 ) = 40", "(1 x 4 x 2 x 10 ) = 80", "(1 x 4 x 2 x 2 x 10 ) = 160")), row.names = c(NA, -6L), class = "data.frame")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/404923.html
標籤:
上一篇:為什么英語函式在RStudio的ifelse中不起作用?
下一篇:六個月前的總和數值變數
