I'm trying to create inverse distance weighted rasters using gstat()
and raster::interpolate()
. I'm running into issues passing a column name to the formula argument of the gstat function.
Hardcoding the column name works just fine:
gs <- gstat(formula=v1~1, locations = data)
r <- raster(shape, res=1000, crs = crs(data))
idw <- raster::interpolate(r, gs)
idwr <- mask(r, gs)
plot(idwr)
Wrapping this into a function so I can loop through multiple column names throws an error:
apply_gstat <- function(col_name, data = data, shape = shape) {
gs <- gstat(formula=col_name~1, locations = data)
r <- raster(shape, res=1000, crs = crs(data))
## interpolate() throws an error because of issue with gstat
idw <- raster::interpolate(r, gs)
idwr <- mask(r, gs)
plot(idwr)
}
col_names <- c("v1", "v2", "v3")
lapply(col_names, function(x) {
gstat_apply(col_name = x, data = data, shape = shape)
}
Error in predict.gstat(model, blockvals, debug.level = debug.level, ...) :
too many spatial dimensions: 18
In addition: Warning message:
In predict.gstat(model, blockvals, debug.level = debug.level, ...) :
NAs introduced by coercion
It will probably work if you use
as.formula(paste(col_name, '~1'))
Here is a self-contained example: