[GIS] R – IDW interpolation using gstat

gstatinterpolationinverse-distance-weightedr

It contains two coordinate columns dist for distance in x direction and rel_alt for an altitude in y direction. The other two columns are the data points for each combination of those two coordinate values.

I am now trying to do a IDW interpolation on the ff column. This is what I tried:

#read the data
dat <- read.csv("data.csv")
#create the grid
x.range <- c(min(dat$dist), max(dat$dist))
y.range <- c(min(dat$rel_alt), max(dat$rel_alt))
grd <- expand.grid(x = seq(from = x.range[1], to = x.range[2], by = 1), 
                   y = seq(from = y.range[1], to = y.range[2], by = 1))
#convert to SpatialPixels 
coordinates(grd) <- ~x + y
gridded(grd) <- TRUE

neighbors = length(dat$ff)
beta = 2

idw_ff = gstat(formula = ff ~ 1, 
                 data = dat, 
                 nmax = neighbors, 
                 set = list(idp = beta))

grid.ff <- predict(object = idw_ff, newdata = grd)

But I am getting an Error message saying:

Error in cbind(dataLst[[1]]$data@bbox[cbind(c(1, 1, 1, 1), c(1, 2, 1,  : 
  trying to get slot "bbox" from an object (class "data.frame") that is not an S4 object 

I don't get the Error, as the grd data is an S4 object. And I am not really sure if that what I am doing even would work properly?

Best Answer

At this point dat isn't a spatial object, so when predict refers back to it it can't get any spatial data:

idw_ff = gstat(formula = ff ~ 1, 
                 data = dat, 
                 nmax = neighbors, 
                 set = list(idp = beta))

make it spatial:

coordinates(dat)=~dist+rel_alt

and it works.

idw_ff = gstat(formula = ff ~ 1, 
                 data = dat, 
                 nmax = neighbors, 
                 set = list(idp = beta))

grid.ff <- predict(object = idw_ff, newdata = grd)

[Note this is going to take a while to compute, but newdata=grd[1:100,] shows it runs in principle]