使用for循环预测多个列

时间:2013-09-05 08:19:22

标签: r smoothing forecasting

我是R(和编程)的新手,我必须为216种不同的产品做出简单的指数平滑预测。

示例:

items <- dataset 

Date     A      B      C  
01-10    3      1      7 
02-10    4      2      0  
03-10    9      2      1 
04-10    8      1      3  

我得到了:

for(i in 1:ncol(items)) { 
  col <- ts(items[,i]) 
  fcast <- ses(col, h=12) 
  write.table(fcast, file ="test.csv",sep=";", dec=",") 
} 

Error: not compatible with REALSXP

我做错了什么,还是我走在正确的轨道上?...请帮帮我

1 个答案:

答案 0 :(得分:0)

这应该有效:

# library("forecast")
for(i in 1:ncol(items)) { 
  col <- ts(items[,i]) 
  fcast <- ses(col, h=12) 
  write.table(fcast, file =paste("test", i, ".csv", sep="") ,sep=";", dec=",") 
} 

Althogh我的代码没有任何错误。

我的示例itemdata.framedput输出:

structure(list(Date = structure(1:4, .Label = c("01-10", "02-10", 
"03-10", "04-10"), class = "factor"), A = c(3L, 4L, 9L, 8L), 
    B = c(1L, 2L, 2L, 1L), C = c(7L, 0L, 1L, 3L)), .Names = c("Date", 
"A", "B", "C"), class = "data.frame", row.names = c(NA, -4L))

其中第一列为factor,其他列为integer