我有一个显示的数据库,并希望根据一列中的一个值计算下面的行总和。
例如:
有人知道如何进行R?
答案 0 :(得分:0)
假设' Safety_Stocks'对于每个'产品,我们都可以使用data.table
。转换' data.frame'到' data.table' (setDT(df1)
),按产品'分组,通过指定' n'获取lead
值shift
。作为' Safety_Stocks'的第一个元素序列,使用Reduce
获取相应list
元素的总和,并将输出分配(:=
)到新列(' New_SafetyStocks&#39)。
library(data.table)
setDT(df1)[, New_SafetyStocks := Reduce(`+`, shift(Sales_Forecast,
type="lead", n=seq(Safety_Stocks[1L]))) , by = Product]
df1
# Product Sales_Forecast Safety_Stocks New_SafetyStocks
# 1: Product A 100 2 300
# 2: Product A 100 2 300
# 3: Product A 200 2 400
# 4: Product A 100 2 600
# 5: Product A 300 2 400
# 6: Product A 300 2 200
# 7: Product A 100 2 300
# 8: Product A 100 2 500
# 9: Product A 200 2 400
#10: Product A 300 2 200
#11: Product A 100 2 NA
#12: Product A 100 2 NA
#13: Product B 500 3 2000
#14: Product B 500 3 3000
#15: Product B 1000 3 3500
#16: Product B 500 3 3500
#17: Product B 1500 3 2500
#18: Product B 1500 3 2000
#19: Product B 500 3 3000
#20: Product B 500 3 3000
#21: Product B 1000 3 2500
#22: Product B 1500 3 NA
#23: Product B 500 3 NA
#24: Product B 500 3 NA
<
df1 <- data.frame(Product = rep(c("Product A", "Product B"), each = 12),
Sales_Forecast = c(100, 100, 200, 100, 300, 300, 100, 100, 200, 300,
100, 100, 500, 500, 1000, 500, 1500, 1500, 500, 500, 1000, 1500, 500, 500),
Safety_Stocks = rep(c(2,3), each = 12))