croston方法应如何应用于数据集

时间:2018-07-31 06:30:39

标签: r forecast

我有一个数据集,显示了250种产品的每月需求。
我在R中导入了数据。我想将此数据集应用croston方法并将结果写入文件,但是我不知道如何逐行应用公式并将其写入文件。我有这样的表:

     product   D1 D2 D3 D3 D4....
     DV400767  6  1  3  1 17  0  5  0   0   1   0   3   0
     DV557119  6  3  2  1 16  0  0  0   0   0   1   0  10
     DV596323  0  0  2  1  2  0  2  9   0   3   0   0   2

我正在尝试通过这些代码查找结果,但是crost函数仅应用于一列

data<-read.csv("data.csv", header=TRUE)
crost(data, h=1,w=0.3, init=c(1,1))

我知道我有错误,如何改善功能?还是需要创建一个循环?

1 个答案:

答案 0 :(得分:0)

您可以转置data.frame并使用apply函数:

data <- read.table(text = "
DV400767  6  1  3  1 17  0  5  0   0   1   0   3   0
DV557119  6  3  2  1 16  0  0  0   0   0   1   0  10
DV596323  0  0  2  1  2  0  2  9   0   3   0   0   2")
names(data) <- c("product", paste0("D", 1:13))

rownames(data) <- data$product
data_t <- as.data.frame(t(data[, -1]))

library(tsintermittent)
models <- apply(data_t, 2, crost, h = 1, w = 0.3, init = c(1,1))

# Print information of the fist product: DV400767
list(names(data_t)[1], models[[1]])

输出:

[[1]]
[1] "DV400767"

[[2]]
[[2]]$`model`
[1] "croston"

[[2]]$frc.in
 [1]          NA 2.750000178 2.531250137 2.602272849 2.317170902 5.293018040 5.293018040 4.268771415 4.268771415 4.268771415
[11] 2.537046096 2.537046096 2.230787775

[[2]]$frc.out
[1] 2.230787775

[[2]]$weights
[1] 0.3 0.3

[[2]]$initial
[1] 8.249999748 2.999999714

[[2]]$components
[[2]]$components$`c.in`
           Demand    Interval
 [1,]          NA          NA
 [2,] 8.249999748 2.999999714
 [3,] 6.074999823 2.399999800
 [4,] 5.152499876 1.979999860
 [5,] 3.906749913 1.685999902
 [6,] 7.834724939 1.480199931
 [7,] 7.834724939 1.480199931
 [8,] 6.984307458 1.636139952
 [9,] 6.984307458 1.636139952
[10,] 6.984307458 1.636139952
[11,] 5.189015220 2.045297966
[12,] 5.189015220 2.045297966
[13,] 4.532310654 2.031708576

[[2]]$components$c.out
          Demand    Interval
[1,] 4.532310654 2.031708576

[[2]]$components$coeff
[1] 1