I am attempting to execute an idw interpolation with gstat but am unable to.
text =
name,long,lat,waterLevel,elevation,depth
EM_01,18.553392,-34.07027,14.4,20.358,63.0
EM_27,18.574777,-34.068709,16.196,19.966,48.0
EM_29,18.613985,-34.053271,18.766,25.477,39.0
EM_20,18.654089,-34.045177,20.102,36.502,45.0
EM_23,18.643495,-34.037468,22.915,32.715,33.0
EM_13,18.637267,-34.029194,25.516,29.716,33.0
install.packages("sf")
install.packages("gstat")
install.packages("units")
install.packages("terra")
library(sf)
library(gstat) # geostatistics
library(units) # units of measure
library(terra)
file = 'text.txt'
#-- import
cfaq <- read.csv(file, header = 1, sep = ',', dec = '.')
#- set as a spatial feature with xy coords an existing projection
cfaq.sf <- st_as_sf(cfaq, coords=c("long", "lat"), crs = 4326)
#- transform to local crs
cfaq.sf <- st_transform(cfaq.sf, crs = 32734)
#-- construct empty grid
(n.col <- length(seq.e <- seq(min.x <- floor(min(st_coordinates(cfaq.sf)[,2])/1000)*1000,
max.x <- ceiling(max(st_coordinates(cfaq.sf)[,2])/1000)*1000, by=1000)))
(n.row <- length(seq.n <- seq(min.y <- floor(min(st_coordinates(cfaq.sf)[,1])/1000)*1000,
max.y <- ceiling(max(st_coordinates(cfaq.sf)[,1])/1000)*1000, by=1000)))
#- 2km grid
grid2km <- rast(nrows = n.row, ncols = n.col,
xmin=min.x, xmax=max.x,
ymin=min.y, ymax=max.y, crs = st_crs(cfaq.sf)$proj4string,
resolution = 2000, names="waterLevel")
values(grid2km) <- NA_real_
#-- grid to df
grid2km.df <- as.data.frame(grid2km, xy = TRUE, na.rm = FALSE)
names(grid2km.df)[1:2] <- c("X", "Y") # match the names of the point dataset
#- idw
grid2km.df$idwp05 = idw(log(waterLevel) ~ 1, cfaq.sf,
grid2km.df, idp = 0.5)$var1.pred
The idw does not succeed.
Error in .local(formula, locations, ...) : sf::st_crs(locations) == sf::st_crs(newdata) is not TRUE
How can this be? The crs
is defined.
How do I execute the idw successfully please?