I'm trying to create a raster filled with semivariogram outputs such as the sill and range of an area which describes the spatial autocorrelation. I wanted to try using the focal function in R as a way to scan an area, and the variogram function from gstat package to calculate sill and range.
I've tried the following code, but there are issues with the function.
library(raster)
library(gstat)
r <- raster()
r[] <- 1:ncell(r)
ra <- aggregate(r, 5)
plot(ra)
v<-variogram(layer~1,as(ra,"SpatialPixelsDataFrame"))
plot(v)
f = fit.variogram(v, vgm("Sph"))
f$psill[2]
f$range
var.sill<-function(x){
names(x)<-c("layer")
v<-variogram(layer~1,as(x,"SpatialPixelsDataFrame"))
f = fit.variogram(v, vgm("Sph"))
f$psill[2]
}
var.sill(ra)
# 374758092
## in a window surrounding each focal cell
rpsill <- focal(ra, w=matrix(1/225, ncol=15, nrow=15), fun=var.sill)
plot(rpsill)
The error states," Error in as(x, "SpatialPixelsDataFrame") : no method or default for coercing “numeric” to “SpatialPixelsDataFrame” "
I would appreciate any help with this or if there is another way to potential create these new rasters please let me know too.
Thank you.