简体   繁体   中英

R Studio - How to predict row-by-row and use previous prediction in next one - linear model

Sorry if this is unclear, had trouble titling this.

Basically I have a linear model that predicts sales and one of the factors is the previous 10 days of sales. So, when predicting for the next month, I need an estimated number for what the "previous 10 days of sales" is for each day in the month.

I want to use the model to generate these numbers - so, for the first day I'm trying to predict, I have the actual number for the last 10 days of sales. For the day after that, I have 9 days of real data, plus the one predicted number generated. For the day after that, 8 days of real data and two generated, etc.

Not quite sure how to implement this and would appreciate any help. Thanks so much.

The first thing that came to mind would be a moving average using the predicted data. This gets hard to defend though once you're averaging only predicted data but its a place to start.

moving.average = 0

test.dat = rnorm(100, 10,2)

for(i in 1:30){
  moving.average[i] = mean(test.dat[i:i+10])
}

Hope this is helpful

Kathy, get your first 10 data points from... where-ever. Seed your prediction with it.

initialization <- c(9.463, 9.704, 10.475, 8.076, 8.221, 8.509, 
            10.083, 9.572, 8.447, 10.081)

prediction = initialization

Here's a silly prediction function that uses the last 10 values:

predFn <- function(vec10){
  stopifnot(length(vec10) == 10)
  round(mean(vec10) + 1 , 3)
}

Although I usually like to use the map family, this one seems like it wants to be a loop

for(i in 11:20){
  lo = i - 10
  hi = i - 1
  prediction[i] <- predFn(prediction[lo:hi])
}

What did we get?

prediction
#  [1]  9.463  9.704 10.475  8.076  8.221  8.509 10.083  9.572  8.447 10.081 10.263 10.343 10.407 10.400 10.633 10.874 11.110 11.213
# [19] 11.377 11.670

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM