Introducción

Configuración

Se inicia limpiando la memoria

rm(list=ls())

Posteriormente se realiza la instalacion de las librerias requeridas para los distintos procesos a realizar en el cuaderno.

#install.packages('XML')
#install.packages('rgdal')
#install.packages('gdalUtils')
#install.packages('sf')
#install.packages('dplyr')
#install_github("envirometrix/landmap")
#install.packages(leaflet)
#install.packages(mapview)
##install.packages("devtools")
##devtools:::install_github('gearslaboratory/gdalUtils')

Ahora se cargan las librerias

library(XML)
library(gdalUtilities)
library(raster)
## Loading required package: sp
library(stars)
## Loading required package: abind
## Loading required package: sf
## Linking to GEOS 3.9.3, GDAL 3.5.2, PROJ 8.2.1; sf_use_s2() is TRUE
## 
## Attaching package: 'sf'
## The following object is masked from 'package:gdalUtilities':
## 
##     gdal_rasterize
library(sf)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:raster':
## 
##     intersect, select, union
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(RColorBrewer)
library(mapview)
library(tmap)
## Breaking News: tmap 3.x is retiring. Please test v4, e.g. with
## remotes::install_github('r-tmap/tmap')
library (devtools)
## Loading required package: usethis
install_github ("JoshOBrien/gdalUtilities")
## WARNING: Rtools is required to build R packages, but is not currently installed.
## 
## Please download and install Rtools 4.2 from https://cran.r-project.org/bin/windows/Rtools/.
## Downloading GitHub repo JoshOBrien/gdalUtilities@HEAD
## 
## ── R CMD build ─────────────────────────────────────────────────────────────────
## WARNING: Rtools is required to build R packages, but is not currently installed.
## 
## Please download and install Rtools 4.2 from https://cran.r-project.org/bin/windows/Rtools/.
##   
  
  
   checking for file 'C:\Windows\Temp\RtmpuejZiW\remotes5184af82cb5\JoshOBrien-gdalUtilities-3d87b46/DESCRIPTION' ...
  
   checking for file 'C:\Windows\Temp\RtmpuejZiW\remotes5184af82cb5\JoshOBrien-gdalUtilities-3d87b46/DESCRIPTION' ... 
  
✔  checking for file 'C:\Windows\Temp\RtmpuejZiW\remotes5184af82cb5\JoshOBrien-gdalUtilities-3d87b46/DESCRIPTION' (7.4s)
## 
  
  
  
─  preparing 'gdalUtilities': (10s)
##    checking DESCRIPTION meta-information ...
  
✔  checking DESCRIPTION meta-information
## 
  
  
  
─  installing the package to process help pages (375ms)
## 
  
  
  
─  saving partial Rd database (1m 12s)
## 
  
  
  
─  checking for LF line-endings in source and make files and shell scripts (851ms)
## 
  
─  checking for empty or unneeded directories
## 
  
  
  
   
  
   building 
  
   building 'gdalUtilities_1.2.5.tar.gz'
  
─  building 'gdalUtilities_1.2.5.tar.gz'
## 
  
   
## 
## Warning: package 'gdalUtilities' is in use and will not be installed
list.files()
##  [1] "Datos"                     "Informe_Suelos.nb.html"   
##  [3] "Informe_Suelos.Rmd"        "MGN_MPIO_POLITICO.CPG"    
##  [5] "MGN_MPIO_POLITICO.dbf"     "MGN_MPIO_POLITICO.prj"    
##  [7] "MGN_MPIO_POLITICO.sbn"     "MGN_MPIO_POLITICO.sbx"    
##  [9] "MGN_MPIO_POLITICO.shp"     "MGN_MPIO_POLITICO.shp.xml"
## [11] "MGN_MPIO_POLITICO.shx"     "MGN2018_MPIO_POLITICO.rar"
## [13] "soc_igh_15_30.tif"

Se define las URL de donde se van a obtener los datos, en este caso sera del ISRIC.

url = "https://files.isric.org/soilgrids/latest/data/" # Path to the webDAV data.

Se indica que objetos se necesita obtener del ISRIC

# basic strings
voi = "soc" # soil organic carbon 
depth = "15-30cm"
quantile = "mean"
# concatenate the strings
(variable = paste(url, voi, sep=""))
## [1] "https://files.isric.org/soilgrids/latest/data/soc"

Ahora se define la propiedad del suelo que se desea evaluar:

#
(layer = paste(variable,depth,quantile, sep="_")) # layer of interest 
## [1] "https://files.isric.org/soilgrids/latest/data/soc_15-30cm_mean"

Luego se especifica la propiedad del VRT:

(vrt_layer = paste(layer, '.vrt', sep=""))
## [1] "https://files.isric.org/soilgrids/latest/data/soc_15-30cm_mean.vrt"

Descargar la región de interes

(cdoba = st_read("./MGN_MPIO_POLITICO.shp"))
## Reading layer `MGN_MPIO_POLITICO' from data source 
##   `C:\Users\SEBAS\Downloads\GB2\Trabajo_Final\MGN_MPIO_POLITICO.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 1182 features and 11 fields
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: -81.73562 ymin: -4.229406 xmax: -66.84722 ymax: 13.39473
## Geodetic CRS:  WGS 84
(cdoba2 = dplyr::filter(cdoba, DPTO_CNMBR == "CÓRDOBA"))

Ahora se reproyecta la capa usando libreria sf:

igh='+proj=igh +lat_0=0 +lon_0=0 +datum=WGS84 +units=m +no_defs'
cdoba_igh <- st_transform(cdoba2, igh)

Ahora se delimita el área que se desea trabajar:

(bbox <- st_bbox(cdoba_igh))
##     xmin     ymin     xmax     ymax 
## -8540444   817874 -8353826  1051719

Ahora se definen los limites del recuadro en donde se quire trabajar:

## ul means upper left
## lr means lower right
ulx = bbox$xmin
uly = bbox$ymax
lrx= bbox$xmax
lry = bbox$ymin
(bb <- c(ulx, uly, lrx, lry))
##     xmin     ymax     xmax     ymin 
## -8540444  1051719 -8353826   817874

Ahora se puede usar la funcion gdal_translate para descargar el VRT pero primero se debe buscar el directorio en donde se guardara.

sg_url="/vsicurl/https://files.isric.org/soilgrids/latest/data/"
datos = 'soc/soc_15-30cm_mean.vrt'
file = "soc_igh_15_30.tif"
gdal_translate(paste0(sg_url,datos), file ,
               tr=c(250,250),
               projwin=bb,
               projwin_srs =igh)

Si se dividen las unidades de los factore se pueden obtener valores más convencionales:

(cdoba_soc <- raster(file)/10)
## class      : RasterLayer 
## dimensions : 935, 746, 697510  (nrow, ncol, ncell)
## resolution : 250, 250  (x, y)
## extent     : -8540500, -8354000, 818000, 1051750  (xmin, xmax, ymin, ymax)
## crs        : +proj=igh +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs 
## source     : memory
## names      : soc_igh_15_30 
## values     : 7.8, 183.3  (min, max)

Revisión de datos

hist(cdoba_soc)

Y ahora un compendio:

summary(cdoba_soc)
##         soc_igh_15_30
## Min.              7.8
## 1st Qu.          18.9
## Median           25.9
## 3rd Qu.          36.7
## Max.            183.3
## NA's          68033.0

Finalmente se realoza el ploteo:

(ncdoba_soc <- st_as_stars(cdoba_soc))
## stars object with 2 dimensions and 1 attribute
## attribute(s):
##                Min. 1st Qu. Median     Mean 3rd Qu.  Max.  NA's
## soc_igh_15_30   7.8    18.9   25.9 30.50764    36.7 183.3 68033
## dimension(s):
##   from  to   offset delta                       refsys x/y
## x    1 746 -8540500   250 +proj=igh +lon_0=0 +x_0=0... [x]
## y    1 935  1051750  -250 +proj=igh +lon_0=0 +x_0=0... [y]
names(ncdoba_soc) <-  "soc"

Se coloca una paleta de color.

pal <- colorRampPalette(brewer.pal(9, "BrBG"))

Ahora se procede a visualizar el mapa

tm_shape(ncdoba_soc) +
  tm_raster("soc", palette = pal(10), title = "SOC [%]", )  +  
  tm_shape(cdoba2) + tm_borders() + tm_text("MPIO_CNMBR", size=0.5) +
  tm_layout(scale = .8, 
    legend.position = c("left","bottom"),
    legend.bg.color = "white", legend.bg.alpha = .2, 
    legend.frame = "gray50")

Referencias

Lizarazo, I. 2023. How to download soil data from SoilGrids. Available at: https://rpubs.com/ials2un/gettingSoilGrids

sessionInfo()
## R version 4.2.3 (2023-03-15 ucrt)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 19045)
## 
## Matrix products: default
## 
## locale:
## [1] LC_COLLATE=Spanish_Colombia.utf8  LC_CTYPE=Spanish_Colombia.utf8   
## [3] LC_MONETARY=Spanish_Colombia.utf8 LC_NUMERIC=C                     
## [5] LC_TIME=Spanish_Colombia.utf8    
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] devtools_2.4.5      usethis_2.2.2       tmap_3.3-4         
##  [4] mapview_2.11.2      RColorBrewer_1.1-3  dplyr_1.1.4        
##  [7] stars_0.6-4         sf_1.0-14           abind_1.4-5        
## [10] raster_3.6-26       sp_2.1-1            gdalUtilities_1.2.5
## [13] XML_3.99-0.15      
## 
## loaded via a namespace (and not attached):
##  [1] fs_1.6.3           satellite_1.0.4    rprojroot_2.0.4    tools_4.2.3       
##  [5] profvis_0.3.8      bslib_0.5.1        utf8_1.2.4         R6_2.5.1          
##  [9] KernSmooth_2.23-20 DBI_1.1.3          colorspace_2.1-0   urlchecker_1.0.1  
## [13] tidyselect_1.2.0   prettyunits_1.2.0  processx_3.8.2     leaflet_2.2.1     
## [17] curl_5.1.0         compiler_4.2.3     leafem_0.2.3       cli_3.6.1         
## [21] desc_1.4.2         sass_0.4.7         scales_1.2.1       classInt_0.4-10   
## [25] callr_3.7.3        proxy_0.4-27       stringr_1.5.1      digest_0.6.33     
## [29] rmarkdown_2.25     base64enc_0.1-3    dichromat_2.0-0.1  pkgconfig_2.0.3   
## [33] htmltools_0.5.7    sessioninfo_1.2.2  highr_0.10         fastmap_1.1.1     
## [37] htmlwidgets_1.6.2  rlang_1.1.2        rstudioapi_0.15.0  shiny_1.8.0       
## [41] jquerylib_0.1.4    generics_0.1.3     jsonlite_1.8.7     crosstalk_1.2.0   
## [45] magrittr_2.0.3     Rcpp_1.0.11        munsell_0.5.0      fansi_1.0.5       
## [49] lifecycle_1.0.4    terra_1.7-55       stringi_1.8.1      leafsync_0.1.0    
## [53] yaml_2.3.7         tmaptools_3.1-1    pkgbuild_1.4.2     grid_4.2.3        
## [57] parallel_4.2.3     promises_1.2.1     crayon_1.5.2       miniUI_0.1.1.1    
## [61] lattice_0.20-45    knitr_1.45         ps_1.7.5           pillar_1.9.0      
## [65] codetools_0.2-19   stats4_4.2.3       pkgload_1.3.3      glue_1.6.2        
## [69] evaluate_0.23      remotes_2.4.2.1    png_0.1-8          vctrs_0.6.4       
## [73] httpuv_1.6.12      purrr_1.0.2        cachem_1.0.8       xfun_0.41         
## [77] mime_0.12          lwgeom_0.2-13      xtable_1.8-4       e1071_1.7-13      
## [81] later_1.3.1        class_7.3-21       viridisLite_0.4.2  tibble_3.2.1      
## [85] memoise_2.0.1      units_0.8-4        ellipsis_0.3.2