0

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.

  • The error occurs because `var.sill` expects a Spatial object, whereas focal provides a vector of numbers. There is no direct way to use focal for your needs, and I do not know of a function that provides a moving window that would support what you need. It would be interesting to write one, but I cannot do it now. You could loop over cells, and use adjacent to get the neighboring cells, then get the coordinates from these cells... It would be slow but possible. – Robert Hijmans Jul 31 '19 at 17:33
  • Thank you for your input anyway! I think I may have found a different approach by splitting the raster in many smaller grids and piecing it back together with the output values. – Melinda Martinez Aug 01 '19 at 15:01
  • If anyone in the future is interested I borrowed code from: https://stackoverflow.com/questions/29784829/r-raster-package-split-image-into-multiples – Melinda Martinez Aug 01 '19 at 15:02

0 Answers0