0

I have been working on an exercise using Rstudio. I want to do a kriging interpolation, but I get an error that I have not been able to solve.

I'd appreciate if some of you could tell me how to fix it.

Here my code:

#importing libraries

library(raster)
library(sf)
library(sp)
library(rgdal)
library(gstat)
library(tmap)
library(tidyverse)

#reading csv data

id <- "1u18s9g15USnzNhj-t2EEFYHsW6GZEIgd" # google file ID
read.csv(sprintf("https://docs.google.com/uc?id=%s&export=download", id))

silver_data = read.csv(sprintf("https://docs.google.com/uc?id=%s&export=download", id))

#creating spatial dataframe

silver_2 <- st_as_sf(silver_data, coords = c("long", "lat"))

st_crs(silver_2) <- 4326

#coordinates transformation

silver_utm2 <- st_transform(silver_2, crs=9155)

#setting variogram

ve <- variogram(silver ~ 1, silver_utm2, cutoff = 5000,width = 200) 
plot(ve, plot.numbers = T, asp=1)

#  experimental variogram
vt <- vgm(psill = 350, model = "Sph", range = 2000,nugget = 0) 
plot(ve, pl = T, model = vt)

#automatic adjustment

va <- fit.variogram(ve, vt) 
plot(ve, pl = T, model = va)

#empty raster in order to create grid for kriging interpolation

z <- raster(as(silver_utm2, "Spatial"), ncols = 200, nrows = 80)

# using raster to create grid

grilla2 <- rasterToPoints(z, spatial = TRUE)
gridded(grilla2) <- TRUE
grilla2 <- as(grilla2, "SpatialPixels")

# using kriging function


ok <- krige(silver~1, locations=silver_utm2, newdata=grilla2, model=va)

The error that appears:


> ok <- krige(silver~1, locations=silver_utm2, newdata=grilla2, model=va)
Error in UseMethod("st_crs<-") : 
  no applicable method for 'st_crs<-' applied to an object of class "c('SpatialPixels', 'SpatialPoints', 'Spatial', 'SpatialVector')


The tutorial I'm following is https://rstudio-pubs-static.s3.amazonaws.com/416462_1463d00750c54fce89955a925eaa4957.html, but the data are not the same.

AndrewGB
  • 16,126
  • 5
  • 18
  • 49
Edmundo
  • 11
  • 1
  • You might have more luck on the [GIS stackexchange](https://gis.stackexchange.com/) with this question. – AndrewGB Jul 03 '21 at 17:33

1 Answers1

0

st_crs() is a function from the package sf and is designed to operate on sf objects only. As your code stands, grilla2 is an sp object. Convert it to sf before using krige().

grilla2 <- sf::st_as_sf(grilla2)
Skaqqs
  • 4,010
  • 1
  • 7
  • 21