De que trata este cuaderno

Este cuaderno de R ilustra funcionalidades del paquete terra, sf, y RasterVis, para realizar recortes de elevaciones. También aprendimos a hacer ploteos ordinarios y ploteos elegantes. aprendimos que no hay que creer en todos :p

TITULO DE NIVEL 2

Try executing this chunk by clicking the Run button within the chunk or by placing your cursor inside it and pressing Ctrl+Shift+Enter.

TITULO DE NIVEL 3

library(terra) #archivos raster
## terra 1.8.54
library(rasterVis) #visualizacion raster
## Cargando paquete requerido: lattice
library(sf)
## Linking to GEOS 3.13.0, GDAL 3.10.1, PROJ 9.5.1; sf_use_s2() is TRUE
library(RColorBrewer)
library(ggplot2)
library(tidyterra)
## 
## Adjuntando el paquete: 'tidyterra'
## The following object is masked from 'package:stats':
## 
##     filter

Add a new chunk by clicking the Insert Chunk button on the toolbar or by pressing Ctrl+Alt+I.

When you save the notebook, an HTML file containing the code and output will be saved alongside it (click the Preview button or press Ctrl+Shift+K to preview the HTML file).

(r <- rast(nrows=40, ncols=20, xmin=0, xmax=5, ymin=0, ymax=10))#crea raster vacio con columnas y filas.
## class       : SpatRaster 
## size        : 40, 20, 1  (nrow, ncol, nlyr)
## resolution  : 0.25, 0.25  (x, y)
## extent      : 0, 5, 0, 10  (xmin, xmax, ymin, ymax)
## coord. ref. : lon/lat WGS 84 (CRS84) (OGC:CRS84)

The preview shows you a rendered HTML copy of the contents of the editor. Consequently, unlike Knit, Preview does not run any R code chunks. Instead, the output of the chunk when it was last run in the editor is displayed.

#values(r) <- runif(ncell(r)) distribucion cualquiera estadistica, de numeros aleatorios.
#values(r) <- seq(1,80,.1) organizacion orginal
#values(r) <- seq(80,1,-0.1) valores invertidos.
#values(r) <- seq(1,800,1)
values(r) <- seq(1,20,1)
## Warning: [setValues] values were recycled

texto

plot(r)

text

q <- 100 * r^2

text

plot(q)

text

q
## class       : SpatRaster 
## size        : 40, 20, 1  (nrow, ncol, nlyr)
## resolution  : 0.25, 0.25  (x, y)
## extent      : 0, 5, 0, 10  (xmin, xmax, ymin, ymax)
## coord. ref. : lon/lat WGS 84 (CRS84) (OGC:CRS84) 
## source(s)   : memory
## name        : lyr.1 
## min value   :   100 
## max value   : 40000

text

m <- q < 10 

text

plot(m)

z <- sin(r)

text

plot(z)

list.files()
##  [1] "~$Raster.docx"     "AguaareaMeta.gpkg" "AguaMeta.gpkg"    
##  [4] "CiudadesMeta.gpkg" "ColombiaDatos.qgz" "Datos"            
##  [7] "poligono1.gpkg"    "Raster.docx"       "Raster.nb.html"   
## [10] "Raster.Rmd"        "Raster.tex"        "Raster_files"     
## [13] "ViasMeta.gpkg"

text

elevacion <- rast("Datos/COL_msk_alt_tif/COL_msk_alt.tif")

text

elevacion
## class       : SpatRaster 
## size        : 2136, 1800, 1  (nrow, ncol, nlyr)
## resolution  : 0.008333333, 0.008333333  (x, y)
## extent      : -81.8, -66.8, -4.3, 13.5  (xmin, xmax, ymin, ymax)
## coord. ref. : lon/lat WGS 84 
## source      : COL_msk_alt.tif 
## name        : COL_msk_alt 
## min value   :         -28 
## max value   :        5453
plot(elevacion)

cm <- crop(elevacion, vector, mask=TRUE)

meta <- st_read("Datos/munMeta.gpkg")
## Reading layer `munMeta' from data source 
##   `C:\Users\usuagro\Documents\G2\G2\Datos\munMeta.gpkg' using driver `GPKG'
## Simple feature collection with 1 feature and 9 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -74.9206 ymin: 1.570401 xmax: -71.0749 ymax: 4.860201
## Geodetic CRS:  WGS 84

TERRA ENTIENDA GPKG

meta1 <- vect(meta)

text

meta1
##  class       : SpatVector 
##  geometry    : polygons 
##  dimensions  : 1, 9  (geometries, attributes)
##  extent      : -74.9206, -71.0749, 1.570401, 4.860201  (xmin, xmax, ymin, ymax)
##  coord. ref. : lon/lat WGS 84 (EPSG:4326) 
##  names       :  ID_0   ISO   NAME_0  ID_1 NAME_1       TYPE_1  ENGTYPE_1
##  type        : <num> <chr>    <chr> <num>  <chr>        <chr>      <chr>
##  values      :    53   COL Colombia    20   Meta Departamento Department
##  NL_NAME_1 VARNAME_1
##      <chr>     <chr>
##         NA        NA

recortar raster al departamento del meta

#elev_meta <- crop(elevacion, meta1, mask=TRUE)

Organizaremos el sistema de coordenadas porque vector Geodetic CRS: WGS 84 y raster coord. ref. : lon/lat WGS 84 por lo realizamos con sf.

crs_meta1 <- crs(meta1) 

asignamos este crs a elevacion

crs(elevacion) <- crs_meta1

verificamos que tengan el mismo crs.

crs(elevacion) == crs(meta1)
## [1] TRUE
ext(meta1)
## SpatExtent : -74.9206008911133, -71.0748977661133, 1.5704009532929, 4.86020088195812 (xmin, xmax, ymin, ymax)
plot(meta1)

recortar raster al departamento del meta

elevacion2 <- crop(elevacion, ext(meta1), mask=TRUE)
## Warning: [crop] mask=TRUE is ignored for SpatExtent objects

ploteo

elevacion2
## class       : SpatRaster 
## size        : 395, 461, 1  (nrow, ncol, nlyr)
## resolution  : 0.008333333, 0.008333333  (x, y)
## extent      : -74.91667, -71.075, 1.566667, 4.858333  (xmin, xmax, ymin, ymax)
## coord. ref. : lon/lat WGS 84 (EPSG:4326) 
## source(s)   : memory
## varname     : COL_msk_alt 
## name        : COL_msk_alt 
## min value   :         121 
## max value   :        4090
plot(elevacion2)

Ponerle logica a las coordenadas porque teniamos las mismas coordenadsa de colombia y presuntamente era el del meta.

sessionInfo()
## R version 4.4.2 (2024-10-31 ucrt)
## Platform: x86_64-w64-mingw32/x64
## 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    
## 
## time zone: America/Bogota
## tzcode source: internal
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] tidyterra_0.7.2    ggplot2_4.0.0      RColorBrewer_1.1-3 sf_1.0-21         
## [5] rasterVis_0.51.7   lattice_0.22-6     terra_1.8-54      
## 
## loaded via a namespace (and not attached):
##  [1] tidyr_1.3.1         generics_0.1.4      sass_0.4.10        
##  [4] class_7.3-22        KernSmooth_2.23-24  jpeg_0.1-11        
##  [7] digest_0.6.37       magrittr_2.0.3      evaluate_1.0.3     
## [10] grid_4.4.2          fastmap_1.2.0       jsonlite_2.0.0     
## [13] e1071_1.7-16        DBI_1.2.3           purrr_1.0.4        
## [16] viridisLite_0.4.2   scales_1.4.0        codetools_0.2-20   
## [19] jquerylib_0.1.4     cli_3.6.4           rlang_1.1.5        
## [22] units_0.8-7         withr_3.0.2         cachem_1.1.0       
## [25] yaml_2.3.10         tools_4.4.2         raster_3.6-32      
## [28] parallel_4.4.2      deldir_2.0-4        dplyr_1.1.4        
## [31] interp_1.1-6        vctrs_0.6.5         R6_2.6.1           
## [34] png_0.1-8           zoo_1.8-14          proxy_0.4-27       
## [37] lifecycle_1.0.4     classInt_0.4-11     pkgconfig_2.0.3    
## [40] pillar_1.10.1       bslib_0.9.0         hexbin_1.28.5      
## [43] gtable_0.3.6        glue_1.8.0          Rcpp_1.0.14        
## [46] tidyselect_1.2.1    tibble_3.2.1        xfun_0.52          
## [49] rstudioapi_0.17.1   knitr_1.50          latticeExtra_0.6-31
## [52] farver_2.1.2        htmltools_0.5.8.1   rmarkdown_2.29     
## [55] compiler_4.4.2      S7_0.2.0            sp_2.2-0

Cambiar color al raster.

map.pal(“elevation”, 10)

r <- rast(system.file(“ex/elev.tif”, package=“terra”)) plot(r, col=map.pal(“elevation”))

map.pal()

ggplot() +
  geom_spatraster(data = elevacion2) + 
  scale_fill_whitebox_c(
    palette = "muted",
    labels = scales::label_number(suffix = "[m]"),
    n.breaks = 12,
    guide = guide_legend(reverse = TRUE)
  ) +
  labs(
    fill = "",
    title = "elevación en Meta"
    #subtitle = "Months of April, May and June"
  )

vamos a guardar el archivo de elevacion del Meta

writeRaster(elevacion2, "Datos/ElevacionMeta.tif", overwrite=TRUE)
(elevacionMeta <- rast("Datos/ElevacionMeta.tif"))
## class       : SpatRaster 
## size        : 395, 461, 1  (nrow, ncol, nlyr)
## resolution  : 0.008333333, 0.008333333  (x, y)
## extent      : -74.91667, -71.075, 1.566667, 4.858333  (xmin, xmax, ymin, ymax)
## coord. ref. : lon/lat WGS 84 (EPSG:4326) 
## source      : ElevacionMeta.tif 
## name        : COL_msk_alt 
## min value   :         121 
## max value   :        4090
plot(elevacionMeta)