Skip to main content
4 of 4
clarification with detailed question
Ichsan
  • 165
  • 5

Linear regresion at each raster pixel's value to predict future value (in R language)

I want to predict future value with existing time series raster. For simplicity, I want use linear regression at each raster pixel's value to predict future value

I have successfull run this code. I have read it from:

https://stackoverflow.com/questions/47435206/cant-calculate-pixel-wise-regression-in-r-on-raster-stack-with-fun?rq=1

library(raster) # Example data r <- raster(nrow=15, ncol=10) set.seed(0) # Now I make 6 raster (1 raster/months), then assign each pixel's value randomly s <- stack(lapply(1:6, function(i) setValues(r, rnorm(ncell(r), i, 3)))) names(s) <- paste0('Month', c(1,2,3,4,5,6)) # Extract each pixel values x <- values(s) # Model with linreg m <- lm(Month6 ~ ., data=data.frame(x)) # Prediction raster p <- predict(s, m) 

If you run that code, p will be a raster. But, I still confused. How to make raster in 'Month8' based on 6 previous raster?

What I mean is, each pixels has different linreg equations (where X=Month1, ..., Months6). If I input X=Month8, I will have 150 cells of Y for 8th Month that represent in each pixel of raster.

What I have done

# Lets try make a data frame for clear insight in my data x <- values(s) DF <- data.frame(x) # Make X as month, and y is target. library(data.table) DF_T <- transpose(DF) Month <- seq(1,nrow(DF_T)) DF_T <- cbind(Month, DF_T) # Make prediction for first pixel V1_lr <- lm(V1 ~ Month, data=DF_T) # prediction for 8th Months in a pixel V1_p <- predict(V1_lr, data.frame(Month=8)) V1_p 

This is just one pixel. I want the entire raster

Ichsan
  • 165
  • 5