I want to perform linear regression with a rolling (moving) window with size 5 using raster data.
I tried a code using the raster
package and the function localFun
, and when I am trying to export the residuals I am getting the following error: Error in setValues(x, value) : values must be numeric, logical or factor
. Here is the code:
library(raster)
ntl = raster("path/ntl.tif") # dependent variable
tirs = raster("path/tirs.tif") # independent variable
tirs_aggr = resample(tirs, ntl, method = 'bilinear')
rfun1 <- function(x, y, ...) {
d <- na.omit(data.frame(x, y))
if (nrow(d) < 5) return(NA)
m <- lm(y~x, data = d)
# return intercept
coefficients(m)[1]
}
rfun2 <- function(x, y, ...) {
d <- na.omit(data.frame(x, y))
if (nrow(d) < 5) return(NA)
m <- lm(y~x, data = d)
# return slope
coefficients(m)[2]
}
rfun3 <- function(x, y, ...) {
d <- na.omit(data.frame(x, y))
if (nrow(d) < 5) return(NA)
m <- lm(y~x, data = d)$residuals # doesn't work
# return residuals
# residuals(m) or m$residuals # doesn't work
}
ff = localFun(ntl, tirs_aggr, ngb = 5, fun = rfun1)
ff2 = localFun(ntl, tirs_aggr, ngb = 5, fun = rfun2)
ff3 = localFun(ntl, tirs_aggr, ngb = 5, fun = rfun3) # returns error
My question is this: How can I extract the coefficients and the residuals as raster layers from a moving window linear regression?
The data:
ntl = raster(ncols=116, nrows=98, xmn=509587.9392, xmx=550187.9392, ymn=161637.6238, ymx=195937.6238, crs='+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +units=m +no_defs')
tirs = raster(ncols=409, nrows=344, xmn=509600, xmx=550500, ymn=161700, ymx=196100, crs='+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +units=m +no_defs')