r-spatial / gstat

Spatial and spatio-temporal geostatistical modelling, prediction and simulation
http://r-spatial.github.io/gstat/
GNU General Public License v2.0
195 stars 49 forks source link

krigeTg: error with sf objects #51

Closed javiereliomedina closed 5 years ago

javiereliomedina commented 5 years ago

Hi @edzer , I've tested the KrigeTg function with sf objects but it doesn't work (it works fine with sp objects). Do you know why I'm having this error? Thanks

Error in as(locations, "data.frame") : internal problem in as(): “sf” is(object, "data.frame") is TRUE, but the metadata asserts that the 'is' relation is FALSE

I attache my code:

 library(gstat)
  library(sf)
  library(sp)

####     KrigeTg with simulated data   (sf package)  #####

####  Study area (Site) ####
  x1 <- 23
  x2 <- 24
  y1 <- 55
  y2 <- 56
  rect <- cbind(c(x1,x1,x2,x2,x1),c(y1,y2,y2,y1,y1))
  Site <- st_polygon(list(rect))
  Site <- st_sfc(Site)
  st_crs(Site) <- 4326

####  Random points in the study area ####
  N <- 1000
  X <- runif(N, 23.0001, 23.9999)
  Y <- runif(N, 55.0001, 55.9999)
  Points <- cbind(X,Y)
  Points <- st_as_sf(as.data.frame(Points), coords = c("X", "Y"))
  st_crs(Points) <- 4326

####  Define the gstat object (spatial model) ####
  g_dummy <- gstat(formula = z ~ 1,
                        locations = ~ X + Y,
                        dummy = T,
                        beta = 3,
                        model = vgm(psill = 1.5, model = "Exp", range = 10, nugget = 0.5),
                        nmax  = 100
      )

####  Simulations based on the gstat object ####
  Points <- predict(g_dummy, newdata = Points, nsim = 1)
  Points$Rn    <- exp(Points$sim1)

####  Predictions by grid cells of 0.015 x 0.015 degree  ####
  SPDF <- st_make_grid(Site, cellsize = .015, what = "corners")

####  Variogram ####
  vg <- variogram(log(Rn) ~ 1, Points)   # great-circle distances (km)
  vg_fit <- fit.variogram(vg, vgm("Exp"))
  plot(vg, vg_fit)

####  Interpolation - TransGaussian kriging using Box-Cox transforms (gstat) ####
lambda <- 0
  Pred_TGOK <- krigeTg(Rn ~ 1, Points, SPDF
                     , model = vg_fit
                     , lambda = lambda
                     , maxdist = 40  # km (great-circle distances)
                     , nmax = 100
                     , nmin = 5
  )   

ps. It works fine if I transform "SPDF" and "Points" to sp objects

SPDF <- as_Spatial(SPDF)
Points <- as_Spatial(Points) 
edzer commented 5 years ago

Thanks! Should work, now.