Este documento presenta una sesión de práctica para aplicar conceptos de interpolación espacial, basado en el script del profesor Iván Lizarazo (2021) disponible en RPubs https://rpubs.com/ials2un/laaspint. Se utilizarán dos tipos de datos:
Muestreos de propiedades químicas y físicas del suelo en sistemas productivos de tomate en el departamento de Santander (shapefile y CSV).
Un DEM SRTM descargado de Google Earth Engine (archivo tif).
Se realizarán las siguientes actividades:
Instalación y carga de librerías.
Ajuste del directorio de trabajo.
Lectura y visualización de datos (shapefile y tif).
Interpolación de valores de pH utilizando IDW y Kriging.
Exportación de resultados en formato GeoTIFF.
Validación cruzada de los modelos mediante cálculo de RMSE.
install.packages(c("sf", "stars", "leaflet", "gstat", "automap", "raster", "RColorBrewer"), repos = "https://cloud.r-project.org/")
## package 'sf' successfully unpacked and MD5 sums checked
## package 'stars' successfully unpacked and MD5 sums checked
## package 'leaflet' successfully unpacked and MD5 sums checked
## package 'gstat' successfully unpacked and MD5 sums checked
## package 'automap' successfully unpacked and MD5 sums checked
## package 'raster' successfully unpacked and MD5 sums checked
## package 'RColorBrewer' successfully unpacked and MD5 sums checked
##
## The downloaded binary packages are in
## C:\Users\cuasq\AppData\Local\Temp\RtmpmoKqc2\downloaded_packages
library(sf)
library(stars)
library(leaflet)
library(gstat)
library(automap)
library(raster)
library(RColorBrewer)
getwd() # Muestra el directorio actual
## [1] "D:/Documentos/5 Semestre/Geomatica Básica/R/Taller_de_Interpolacion"
setwd("D:/Documentos/5 Semestre/Geomatica Básica/R/Taller_de_Interpolacion")
getwd() # Verificar el directorio actualizado
## [1] "D:/Documentos/5 Semestre/Geomatica Básica/R/Taller_de_Interpolacion"
ruta_aoi <- "./municipios_muestreo.shp"
ruta_puntos <- "./puntos_muestreo.shp" # Ruta del shapefile de puntos de muestreo
ruta_raster <- "./dem_srtm_9377.tif" # Ruta del DEM (archivo tif)
raster_dem <- read_stars(ruta_raster, RasterIO = list(bands = 1))
print(raster_dem)
## stars object with 2 dimensions and 1 attribute
## attribute(s), summary of first 1e+05 cells:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## dem_srtm_9377.tif -247 0 0 131.274 0 1673
## dimension(s):
## from to offset delta refsys point x/y
## x 1 1754 4966240 29.78 MAGNA-SIRGAS 2018 / Orige... FALSE [x]
## y 1 1428 2297460 -29.78 MAGNA-SIRGAS 2018 / Orige... FALSE [y]
plot(raster_dem)
crs_raster <- st_crs(raster_dem)
print(crs_raster)
## Coordinate Reference System:
## User input: MAGNA-SIRGAS 2018 / Origen-Nacional
## wkt:
## PROJCRS["MAGNA-SIRGAS 2018 / Origen-Nacional",
## BASEGEOGCRS["MAGNA-SIRGAS 2018",
## DATUM["Marco Geocentrico Nacional de Referencia 2018",
## ELLIPSOID["GRS 1980",6378137,298.257222101,
## LENGTHUNIT["metre",1]]],
## PRIMEM["Greenwich",0,
## ANGLEUNIT["degree",0.0174532925199433]],
## ID["EPSG",20046]],
## CONVERSION["Colombia Transverse Mercator",
## METHOD["Transverse Mercator",
## ID["EPSG",9807]],
## PARAMETER["Latitude of natural origin",4,
## ANGLEUNIT["degree",0.0174532925199433],
## ID["EPSG",8801]],
## PARAMETER["Longitude of natural origin",-73,
## ANGLEUNIT["degree",0.0174532925199433],
## ID["EPSG",8802]],
## PARAMETER["Scale factor at natural origin",0.9992,
## SCALEUNIT["unity",1],
## ID["EPSG",8805]],
## PARAMETER["False easting",5000000,
## LENGTHUNIT["metre",1],
## ID["EPSG",8806]],
## PARAMETER["False northing",2000000,
## LENGTHUNIT["metre",1],
## ID["EPSG",8807]]],
## CS[Cartesian,2],
## AXIS["northing (N)",north,
## ORDER[1],
## LENGTHUNIT["metre",1]],
## AXIS["easting (E)",east,
## ORDER[2],
## LENGTHUNIT["metre",1]],
## USAGE[
## SCOPE["Cadastre, topographic mapping."],
## AREA["Colombia - onshore and offshore. Includes San Andres y Providencia, Malpelo Islands, Roncador Bank, Serrana Bank and Serranilla Bank."],
## BBOX[-4.23,-84.77,15.51,-66.87]],
## ID["EPSG",9377]]
puntos <- st_read(ruta_puntos)
## Reading layer `puntos_muestreo' from data source
## `D:\Documentos\5 Semestre\Geomatica Básica\R\Taller_de_Interpolacion\puntos_muestreo.shp'
## using driver `ESRI Shapefile'
## Simple feature collection with 67 features and 16 fields
## Geometry type: POINT
## Dimension: XY
## Bounding box: xmin: 4968206 ymin: 2257635 xmax: 5005157 ymax: 2292361
## Projected CRS: MAGNA-SIRGAS_Origen-Nacional
crs_puntos <- st_crs(puntos)
print(crs_puntos)
## Coordinate Reference System:
## User input: MAGNA-SIRGAS_Origen-Nacional
## wkt:
## PROJCRS["MAGNA-SIRGAS_Origen-Nacional",
## BASEGEOGCRS["GCS_MAGNA-SIRGAS_2018",
## DATUM["Marco Geocentrico Nacional de Referencia 2018",
## ELLIPSOID["GRS 1980",6378137,298.257222101,
## LENGTHUNIT["metre",1]],
## ID["EPSG",1329]],
## PRIMEM["Greenwich",0,
## ANGLEUNIT["Degree",0.0174532925199433]]],
## CONVERSION["unnamed",
## METHOD["Transverse Mercator",
## ID["EPSG",9807]],
## PARAMETER["Latitude of natural origin",4,
## ANGLEUNIT["Degree",0.0174532925199433],
## ID["EPSG",8801]],
## PARAMETER["Longitude of natural origin",-73,
## ANGLEUNIT["Degree",0.0174532925199433],
## ID["EPSG",8802]],
## PARAMETER["Scale factor at natural origin",0.9992,
## SCALEUNIT["unity",1],
## ID["EPSG",8805]],
## PARAMETER["False easting",5000000,
## LENGTHUNIT["metre",1],
## ID["EPSG",8806]],
## PARAMETER["False northing",2000000,
## LENGTHUNIT["metre",1],
## ID["EPSG",8807]]],
## CS[Cartesian,2],
## AXIS["(E)",east,
## ORDER[1],
## LENGTHUNIT["metre",1,
## ID["EPSG",9001]]],
## AXIS["(N)",north,
## ORDER[2],
## LENGTHUNIT["metre",1,
## ID["EPSG",9001]]]]
if (identical(crs_raster, crs_puntos)) {
cat("El sistema de referencia de coordenadas del raster y de los puntos es el mismo:\n")
print(crs_raster)
} else {
cat("Los sistemas de referencia de coordenadas son diferentes.\n")
cat("Raster:\n")
print(crs_raster)
cat("Puntos:\n")
print(crs_puntos)
}
## Los sistemas de referencia de coordenadas son diferentes.
## Raster:
## Coordinate Reference System:
## User input: MAGNA-SIRGAS 2018 / Origen-Nacional
## wkt:
## PROJCRS["MAGNA-SIRGAS 2018 / Origen-Nacional",
## BASEGEOGCRS["MAGNA-SIRGAS 2018",
## DATUM["Marco Geocentrico Nacional de Referencia 2018",
## ELLIPSOID["GRS 1980",6378137,298.257222101,
## LENGTHUNIT["metre",1]]],
## PRIMEM["Greenwich",0,
## ANGLEUNIT["degree",0.0174532925199433]],
## ID["EPSG",20046]],
## CONVERSION["Colombia Transverse Mercator",
## METHOD["Transverse Mercator",
## ID["EPSG",9807]],
## PARAMETER["Latitude of natural origin",4,
## ANGLEUNIT["degree",0.0174532925199433],
## ID["EPSG",8801]],
## PARAMETER["Longitude of natural origin",-73,
## ANGLEUNIT["degree",0.0174532925199433],
## ID["EPSG",8802]],
## PARAMETER["Scale factor at natural origin",0.9992,
## SCALEUNIT["unity",1],
## ID["EPSG",8805]],
## PARAMETER["False easting",5000000,
## LENGTHUNIT["metre",1],
## ID["EPSG",8806]],
## PARAMETER["False northing",2000000,
## LENGTHUNIT["metre",1],
## ID["EPSG",8807]]],
## CS[Cartesian,2],
## AXIS["northing (N)",north,
## ORDER[1],
## LENGTHUNIT["metre",1]],
## AXIS["easting (E)",east,
## ORDER[2],
## LENGTHUNIT["metre",1]],
## USAGE[
## SCOPE["Cadastre, topographic mapping."],
## AREA["Colombia - onshore and offshore. Includes San Andres y Providencia, Malpelo Islands, Roncador Bank, Serrana Bank and Serranilla Bank."],
## BBOX[-4.23,-84.77,15.51,-66.87]],
## ID["EPSG",9377]]
## Puntos:
## Coordinate Reference System:
## User input: MAGNA-SIRGAS_Origen-Nacional
## wkt:
## PROJCRS["MAGNA-SIRGAS_Origen-Nacional",
## BASEGEOGCRS["GCS_MAGNA-SIRGAS_2018",
## DATUM["Marco Geocentrico Nacional de Referencia 2018",
## ELLIPSOID["GRS 1980",6378137,298.257222101,
## LENGTHUNIT["metre",1]],
## ID["EPSG",1329]],
## PRIMEM["Greenwich",0,
## ANGLEUNIT["Degree",0.0174532925199433]]],
## CONVERSION["unnamed",
## METHOD["Transverse Mercator",
## ID["EPSG",9807]],
## PARAMETER["Latitude of natural origin",4,
## ANGLEUNIT["Degree",0.0174532925199433],
## ID["EPSG",8801]],
## PARAMETER["Longitude of natural origin",-73,
## ANGLEUNIT["Degree",0.0174532925199433],
## ID["EPSG",8802]],
## PARAMETER["Scale factor at natural origin",0.9992,
## SCALEUNIT["unity",1],
## ID["EPSG",8805]],
## PARAMETER["False easting",5000000,
## LENGTHUNIT["metre",1],
## ID["EPSG",8806]],
## PARAMETER["False northing",2000000,
## LENGTHUNIT["metre",1],
## ID["EPSG",8807]]],
## CS[Cartesian,2],
## AXIS["(E)",east,
## ORDER[1],
## LENGTHUNIT["metre",1,
## ID["EPSG",9001]]],
## AXIS["(N)",north,
## ORDER[2],
## LENGTHUNIT["metre",1,
## ID["EPSG",9001]]]]
puntos_reproj <- st_transform(puntos, crs_raster)
print(puntos_reproj) # Muestra la tabla de atributos de los puntos
## Simple feature collection with 67 features and 16 fields
## Geometry type: POINT
## Dimension: XY
## Bounding box: xmin: 4968206 ymin: 2257635 xmax: 5005157 ymax: 2292361
## Projected CRS: MAGNA-SIRGAS 2018 / Origen-Nacional
## First 10 features:
## Department Municipali Latitude.D Longitude. Altitude.m pH EC.dSm NH4.ppm
## 1 Santander Confines 6.331580 -73.25827 1533 4.8 0.08 10.3
## 2 Santander Confines 6.345463 -73.28759 1489 4.9 0.07 10.3
## 3 Santander Confines 6.357339 -73.28138 1482 4.8 0.08 18.2
## 4 Santander Confines 6.360368 -73.24903 1581 4.7 0.07 6.7
## 5 Santander Confines 6.340922 -73.20868 1878 4.8 0.15 24.0
## 6 Santander Confines 6.357226 -73.23005 1742 4.8 0.09 11.7
## 7 Santander Confines 6.339062 -73.23301 1752 4.9 0.09 9.4
## 8 Santander Confines 6.402768 -73.22524 1715 4.8 0.08 9.4
## 9 Santander Confines 6.365608 -73.21098 1878 4.8 0.10 19.3
## 10 Santander Paramo 6.384360 -73.19552 1912 4.9 0.12 19.1
## NO3.ppm K2O.ppm P2O5.ppm SOC.pct Sand.pct Silt.pct Clay.pct Slope.pct
## 1 8.4 173.5 10.1 2.46 40.7 32.6 26.6 10.5
## 2 5.4 122.9 8.9 1.62 51.2 26.1 22.6 9.2
## 3 0.9 119.3 6.2 2.95 51.9 35.4 12.7 7.4
## 4 2.3 181.9 12.1 1.02 37.3 36.1 26.5 12.6
## 5 12.3 130.1 7.3 2.48 65.6 30.3 4.1 8.5
## 6 1.2 131.3 4.8 1.60 40.8 46.5 12.6 7.5
## 7 2.0 73.5 11.5 3.65 55.0 42.5 2.5 5.6
## 8 5.9 194.0 6.6 2.12 33.7 45.4 20.9 13.7
## 9 0.3 273.5 3.4 3.81 64.4 24.9 10.6 1.5
## 10 0.1 128.9 18.8 3.14 39.1 50.7 10.3 15.8
## geometry
## 1 POINT (4971447 2257635)
## 2 POINT (4968206 2259171)
## 3 POINT (4968893 2260483)
## 4 POINT (4972470 2260816)
## 5 POINT (4976930 2258665)
## 6 POINT (4974568 2260467)
## 7 POINT (4974240 2258460)
## 8 POINT (4975101 2265500)
## 9 POINT (4976677 2261393)
## 10 POINT (4978386 2263464)
print(names(puntos))
## [1] "Department" "Municipali" "Latitude.D" "Longitude." "Altitude.m"
## [6] "pH" "EC.dSm" "NH4.ppm" "NO3.ppm" "K2O.ppm"
## [11] "P2O5.ppm" "SOC.pct" "Sand.pct" "Silt.pct" "Clay.pct"
## [16] "Slope.pct" "geometry"
print(st_crs(puntos))
## Coordinate Reference System:
## User input: MAGNA-SIRGAS_Origen-Nacional
## wkt:
## PROJCRS["MAGNA-SIRGAS_Origen-Nacional",
## BASEGEOGCRS["GCS_MAGNA-SIRGAS_2018",
## DATUM["Marco Geocentrico Nacional de Referencia 2018",
## ELLIPSOID["GRS 1980",6378137,298.257222101,
## LENGTHUNIT["metre",1]],
## ID["EPSG",1329]],
## PRIMEM["Greenwich",0,
## ANGLEUNIT["Degree",0.0174532925199433]]],
## CONVERSION["unnamed",
## METHOD["Transverse Mercator",
## ID["EPSG",9807]],
## PARAMETER["Latitude of natural origin",4,
## ANGLEUNIT["Degree",0.0174532925199433],
## ID["EPSG",8801]],
## PARAMETER["Longitude of natural origin",-73,
## ANGLEUNIT["Degree",0.0174532925199433],
## ID["EPSG",8802]],
## PARAMETER["Scale factor at natural origin",0.9992,
## SCALEUNIT["unity",1],
## ID["EPSG",8805]],
## PARAMETER["False easting",5000000,
## LENGTHUNIT["metre",1],
## ID["EPSG",8806]],
## PARAMETER["False northing",2000000,
## LENGTHUNIT["metre",1],
## ID["EPSG",8807]]],
## CS[Cartesian,2],
## AXIS["(E)",east,
## ORDER[1],
## LENGTHUNIT["metre",1,
## ID["EPSG",9001]]],
## AXIS["(N)",north,
## ORDER[2],
## LENGTHUNIT["metre",1,
## ID["EPSG",9001]]]]
var <- "pH" # Definir la variable de interés
print(puntos[var]) # Extrae la columna pH
## Simple feature collection with 67 features and 1 field
## Geometry type: POINT
## Dimension: XY
## Bounding box: xmin: 4968206 ymin: 2257635 xmax: 5005157 ymax: 2292361
## Projected CRS: MAGNA-SIRGAS_Origen-Nacional
## First 10 features:
## pH geometry
## 1 4.8 POINT (4971447 2257635)
## 2 4.9 POINT (4968206 2259171)
## 3 4.8 POINT (4968893 2260483)
## 4 4.7 POINT (4972470 2260816)
## 5 4.8 POINT (4976930 2258665)
## 6 4.8 POINT (4974568 2260467)
## 7 4.9 POINT (4974240 2258460)
## 8 4.8 POINT (4975101 2265500)
## 9 4.8 POINT (4976677 2261393)
## 10 4.9 POINT (4978386 2263464)
st_crs(puntos_reproj)
## Coordinate Reference System:
## User input: MAGNA-SIRGAS 2018 / Origen-Nacional
## wkt:
## PROJCRS["MAGNA-SIRGAS 2018 / Origen-Nacional",
## BASEGEOGCRS["MAGNA-SIRGAS 2018",
## DATUM["Marco Geocentrico Nacional de Referencia 2018",
## ELLIPSOID["GRS 1980",6378137,298.257222101,
## LENGTHUNIT["metre",1]]],
## PRIMEM["Greenwich",0,
## ANGLEUNIT["degree",0.0174532925199433]],
## ID["EPSG",20046]],
## CONVERSION["Colombia Transverse Mercator",
## METHOD["Transverse Mercator",
## ID["EPSG",9807]],
## PARAMETER["Latitude of natural origin",4,
## ANGLEUNIT["degree",0.0174532925199433],
## ID["EPSG",8801]],
## PARAMETER["Longitude of natural origin",-73,
## ANGLEUNIT["degree",0.0174532925199433],
## ID["EPSG",8802]],
## PARAMETER["Scale factor at natural origin",0.9992,
## SCALEUNIT["unity",1],
## ID["EPSG",8805]],
## PARAMETER["False easting",5000000,
## LENGTHUNIT["metre",1],
## ID["EPSG",8806]],
## PARAMETER["False northing",2000000,
## LENGTHUNIT["metre",1],
## ID["EPSG",8807]]],
## CS[Cartesian,2],
## AXIS["northing (N)",north,
## ORDER[1],
## LENGTHUNIT["metre",1]],
## AXIS["easting (E)",east,
## ORDER[2],
## LENGTHUNIT["metre",1]],
## USAGE[
## SCOPE["Cadastre, topographic mapping."],
## AREA["Colombia - onshore and offshore. Includes San Andres y Providencia, Malpelo Islands, Roncador Bank, Serrana Bank and Serranilla Bank."],
## BBOX[-4.23,-84.77,15.51,-66.87]],
## ID["EPSG",9377]]
crs(raster_dem)
## [1] NA
g <- gstat(formula = pH ~ 1, data = puntos_reproj, set = list(idp = 2))
z <- predict(g, raster_dem)
## [inverse distance weighted interpolation]
print(z) # Muestra el resultado; contiene 'var1.pred' y (para kriging) 'var1.var'
## stars object with 2 dimensions and 2 attributes
## attribute(s), summary of first 1e+05 cells:
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## var1.pred 5.04681 5.130046 5.162891 5.174822 5.238671 5.283381 0e+00
## var1.var NA NA NA NaN NA NA 1e+05
## dimension(s):
## from to offset delta refsys x/y
## x 1 1754 4966240 29.78 MAGNA-SIRGAS 2018 / Orige... [x]
## y 1 1428 2297460 -29.78 MAGNA-SIRGAS 2018 / Orige... [y]
z <- z["var1.pred",,]
names(z) <- "pH"
b <- seq(4, 7.5, 0.1) # Secuencia para definir intervalos
plot(z, breaks = b, col = hcl.colors(length(b) - 1, "Spectral"), reset = FALSE)
plot(st_geometry(puntos_reproj), pch = 3, add = TRUE)
contour(z, breaks = b, add = TRUE)
interpolacion_idw <- "./ph_idw.tif"
write_stars(z, dsn = interpolacion_idw)
v_emp_ok <- variogram(pH ~ 1, puntos_reproj)
plot(v_emp_ok)
v_mod_ok <- autofitVariogram(pH ~ 1, as(puntos_reproj, "Spatial"))
plot(v_mod_ok)
g <- gstat(formula = pH ~ 1, model = v_mod_ok$var_model, data = puntos_reproj)
z <- predict(g, raster_dem)
## [using ordinary kriging]
print(z)
## stars object with 2 dimensions and 2 attributes
## attribute(s), summary of first 1e+05 cells:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## var1.pred 4.973535 5.0923192 5.1475910 5.1348409 5.18763 5.238132
## var1.var 0.604284 0.7349258 0.8883815 0.9006311 1.04760 1.302663
## dimension(s):
## from to offset delta refsys x/y
## x 1 1754 4966240 29.78 MAGNA-SIRGAS 2018 / Orige... [x]
## y 1 1428 2297460 -29.78 MAGNA-SIRGAS 2018 / Orige... [y]
prediccion <- z["var1.pred",,]
names(prediccion) <- "pH"
b_predict <- seq(4, 7, 0.1)
plot(prediccion, breaks = b_predict, col = hcl.colors(length(b_predict) - 1, "Spectral"), reset = FALSE)
varianza <- z["var1.var",,]
names(varianza) <- "varianza pH"
b_var <- seq(0.1, 1.4, 0.1)
plot(varianza, breaks = b_var, col = hcl.colors(length(b_var) - 1, "Spectral"), reset = FALSE)
ruta_prediccion_idw <- "./ph_idw_prediccion.tif"
ruta_varianza_idw <- "./ph_idw_varianza.tif"
ruta_prediccion_kriging <- "./ph_kriging_prediccion.tif"
ruta_varianza_kriging <- "./ph_kriging_varianza.tif"
if (exists("z")) {
writeRaster(as(z, "Raster"), filename = ruta_prediccion_idw, format = "GTiff", overwrite = TRUE)
cat("Raster de predicción IDW exportado a:", ruta_prediccion_idw, "\n")
}
## Raster de predicción IDW exportado a: ./ph_idw_prediccion.tif
if ("var1.var" %in% names(z)) {
writeRaster(as(z["var1.var",,], "Raster"), filename = ruta_varianza_idw, format = "GTiff", overwrite = TRUE)
cat("Raster de varianza IDW exportado a:", ruta_varianza_idw, "\n")
}
## Raster de varianza IDW exportado a: ./ph_idw_varianza.tif
if (exists("prediccion")) {
writeRaster(as(prediccion, "Raster"), filename = ruta_prediccion_kriging, format = "GTiff", overwrite = TRUE)
cat("Raster de predicción Kriging exportado a:", ruta_prediccion_kriging, "\n")
}
## Raster de predicción Kriging exportado a: ./ph_kriging_prediccion.tif
if (exists("varianza")) {
writeRaster(as(varianza, "Raster"), filename = ruta_varianza_kriging, format = "GTiff", overwrite = TRUE)
cat("Raster de varianza Kriging exportado a:", ruta_varianza_kriging, "\n")
}
## Raster de varianza Kriging exportado a: ./ph_kriging_varianza.tif
ruta_puntos <- "./puntos_muestreo.shp"
ruta_raster <- "./dem_srtm_9377.tif"
raster_dem <- read_stars(ruta_raster, RasterIO = list(bands = 1))
puntos <- st_read(ruta_puntos)
## Reading layer `puntos_muestreo' from data source
## `D:\Documentos\5 Semestre\Geomatica Básica\R\Taller_de_Interpolacion\puntos_muestreo.shp'
## using driver `ESRI Shapefile'
## Simple feature collection with 67 features and 16 fields
## Geometry type: POINT
## Dimension: XY
## Bounding box: xmin: 4968206 ymin: 2257635 xmax: 5005157 ymax: 2292361
## Projected CRS: MAGNA-SIRGAS_Origen-Nacional
puntos_reproj <- st_transform(puntos, st_crs(raster_dem))
puntos_filtrados <- puntos_reproj[puntos_reproj$pH >= 4.5 & puntos_reproj$pH <= 5.0, ]
calcular_rmse <- function(observado, predicho) {
sqrt(mean((observado - predicho)^2))
}
cat("\n--- Validación Cruzada para IDW ---\n")
##
## --- Validación Cruzada para IDW ---
resultados_idw <- vector("numeric", length = nrow(puntos_filtrados))
for (i in 1:nrow(puntos_filtrados)) {
# Dejar un punto fuera para la validación
puntos_entrenamiento <- puntos_filtrados[-i, ]
punto_prueba <- puntos_filtrados[i, ]
# Modelo IDW
modelo_idw <- gstat(formula = pH ~ 1, data = puntos_entrenamiento, set = list(idp = 2))
prediccion_idw <- predict(modelo_idw, punto_prueba)
# Almacenar la predicción
resultados_idw[i] <- prediccion_idw$var1.pred
}
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
## [inverse distance weighted interpolation]
rmse_idw <- calcular_rmse(puntos_filtrados$pH, resultados_idw)
cat("RMSE IDW: ", rmse_idw, "\n")
## RMSE IDW: 0.1382111
cat("\n--- Validación Cruzada para Kriging ---\n")
##
## --- Validación Cruzada para Kriging ---
resultados_kriging <- vector("numeric", length = nrow(puntos_filtrados))
for (i in 1:nrow(puntos_filtrados)) {
puntos_entrenamiento <- puntos_filtrados[-i, ]
punto_prueba <- puntos_filtrados[i, ]
# Crear variograma y ajustar modelo para Kriging
variograma <- variogram(pH ~ 1, puntos_entrenamiento)
modelo_variograma <- autofitVariogram(pH ~ 1, as(puntos_entrenamiento, "Spatial"))
# Modelo Kriging
modelo_kriging <- gstat(formula = pH ~ 1, model = modelo_variograma$var_model, data = puntos_entrenamiento)
prediccion_kriging <- predict(modelo_kriging, punto_prueba)
# Almacenar la predicción
resultados_kriging[i] <- prediccion_kriging$var1.pred
}
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
## [using ordinary kriging]
rmse_kriging <- calcular_rmse(puntos_filtrados$pH, resultados_kriging)
cat("RMSE Kriging: ", rmse_kriging, "\n")
## RMSE Kriging: 0.1417886
print(names(puntos))
## [1] "Department" "Municipali" "Latitude.D" "Longitude." "Altitude.m"
## [6] "pH" "EC.dSm" "NH4.ppm" "NO3.ppm" "K2O.ppm"
## [11] "P2O5.ppm" "SOC.pct" "Sand.pct" "Silt.pct" "Clay.pct"
## [16] "Slope.pct" "geometry"
print(st_crs(puntos))
## Coordinate Reference System:
## User input: MAGNA-SIRGAS_Origen-Nacional
## wkt:
## PROJCRS["MAGNA-SIRGAS_Origen-Nacional",
## BASEGEOGCRS["GCS_MAGNA-SIRGAS_2018",
## DATUM["Marco Geocentrico Nacional de Referencia 2018",
## ELLIPSOID["GRS 1980",6378137,298.257222101,
## LENGTHUNIT["metre",1]],
## ID["EPSG",1329]],
## PRIMEM["Greenwich",0,
## ANGLEUNIT["Degree",0.0174532925199433]]],
## CONVERSION["unnamed",
## METHOD["Transverse Mercator",
## ID["EPSG",9807]],
## PARAMETER["Latitude of natural origin",4,
## ANGLEUNIT["Degree",0.0174532925199433],
## ID["EPSG",8801]],
## PARAMETER["Longitude of natural origin",-73,
## ANGLEUNIT["Degree",0.0174532925199433],
## ID["EPSG",8802]],
## PARAMETER["Scale factor at natural origin",0.9992,
## SCALEUNIT["unity",1],
## ID["EPSG",8805]],
## PARAMETER["False easting",5000000,
## LENGTHUNIT["metre",1],
## ID["EPSG",8806]],
## PARAMETER["False northing",2000000,
## LENGTHUNIT["metre",1],
## ID["EPSG",8807]]],
## CS[Cartesian,2],
## AXIS["(E)",east,
## ORDER[1],
## LENGTHUNIT["metre",1,
## ID["EPSG",9001]]],
## AXIS["(N)",north,
## ORDER[2],
## LENGTHUNIT["metre",1,
## ID["EPSG",9001]]]]
summary(mtcars)
## mpg cyl disp hp
## Min. :10.40 Min. :4.000 Min. : 71.1 Min. : 52.0
## 1st Qu.:15.43 1st Qu.:4.000 1st Qu.:120.8 1st Qu.: 96.5
## Median :19.20 Median :6.000 Median :196.3 Median :123.0
## Mean :20.09 Mean :6.188 Mean :230.7 Mean :146.7
## 3rd Qu.:22.80 3rd Qu.:8.000 3rd Qu.:326.0 3rd Qu.:180.0
## Max. :33.90 Max. :8.000 Max. :472.0 Max. :335.0
## drat wt qsec vs
## Min. :2.760 Min. :1.513 Min. :14.50 Min. :0.0000
## 1st Qu.:3.080 1st Qu.:2.581 1st Qu.:16.89 1st Qu.:0.0000
## Median :3.695 Median :3.325 Median :17.71 Median :0.0000
## Mean :3.597 Mean :3.217 Mean :17.85 Mean :0.4375
## 3rd Qu.:3.920 3rd Qu.:3.610 3rd Qu.:18.90 3rd Qu.:1.0000
## Max. :4.930 Max. :5.424 Max. :22.90 Max. :1.0000
## am gear carb
## Min. :0.0000 Min. :3.000 Min. :1.000
## 1st Qu.:0.0000 1st Qu.:3.000 1st Qu.:2.000
## Median :0.0000 Median :4.000 Median :2.000
## Mean :0.4062 Mean :3.688 Mean :2.812
## 3rd Qu.:1.0000 3rd Qu.:4.000 3rd Qu.:4.000
## Max. :1.0000 Max. :5.000 Max. :8.000
mtcars
## mpg cyl disp hp drat wt qsec vs am gear carb
## Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
## Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
## Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
## Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
## Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
## Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
## Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
## Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
## Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
## Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
## Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4
## Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3
## Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3
## Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3
## Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4
## Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4
## Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4
## Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
## Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
## Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
## Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
## Dodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2
## AMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2
## Camaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4
## Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2
## Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
## Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
## Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
## Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4
## Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6
## Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8
## Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2