##Introducción a Objetos Simples en R

En este cuaderno se usarán entidades simples para crear el departamento de Bolívar

##Configuración

library(sf)
## Linking to GEOS 3.14.1, GDAL 3.12.1, PROJ 9.7.1; sf_use_s2() is TRUE
library(dplyr)
## 
## Adjuntando el paquete: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(ggplot2)
library(ggspatial)

##Lectura y escritura de información espacial

Lectura de información espacial

list.files("./MGN2025_MPIO_GRAFICO")
## [1] "MGN_ADM_MPIO_GRAFICO.cpg"     "MGN_ADM_MPIO_GRAFICO.dbf"    
## [3] "MGN_ADM_MPIO_GRAFICO.prj"     "MGN_ADM_MPIO_GRAFICO.sbn"    
## [5] "MGN_ADM_MPIO_GRAFICO.sbx"     "MGN_ADM_MPIO_GRAFICO.shp"    
## [7] "MGN_ADM_MPIO_GRAFICO.shp.xml" "MGN_ADM_MPIO_GRAFICO.shx"
colombia <- st_read("./MGN2025_MPIO_GRAFICO/MGN_ADM_MPIO_GRAFICO.shp")
## Reading layer `MGN_ADM_MPIO_GRAFICO' from data source 
##   `C:\Users\imthe\Documents\GB2\Proyecto1\Datos\MGN2025_MPIO_GRAFICO\MGN_ADM_MPIO_GRAFICO.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 1122 features and 11 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -81.73562 ymin: -4.229406 xmax: -66.84722 ymax: 13.39473
## Geodetic CRS:  WGS 84
head(colombia)

Escritura de información espacial

st_write(colombia, "Bolivar_municipios.gpkg", driver = "GPKG", append = F)
## Deleting layer `Bolivar_municipios' using driver `GPKG'
## Writing layer `Bolivar_municipios' to data source 
##   `Bolivar_municipios.gpkg' using driver `GPKG'
## Writing 1122 features with 11 fields and geometry type Multi Polygon.
list.files(pattern = "gpkg")
##  [1] "Bolívar para composición.gpkg"   "Bolívar.gpkg"                   
##  [3] "Bolivar_areasdeagua.gpkg"        "Bolivar_carreteras.gpkg"        
##  [5] "Bolivar_lineasdeagua.gpkg"       "Bolivar_municipios.gpkg"        
##  [7] "Ciudades de Bolívar.gpkg"        "Ciudades de Colombia.gpkg"      
##  [9] "Curvas de nivel - Bolívar.gpkg"  "Curvas de nivel - Colombia.gpkg"
## [11] "Delineado de Bolívar.gpkg"       "Departamentos.gpkg"             
## [13] "Elevacion_9377.gpkg"             "Elevacion_9377.gpkg.aux.xml"    
## [15] "Elevacion_9377.gpkg.tif"         "Elevacion_9377.gpkg.tif.aux.xml"
## [17] "ISO_COL.gpkg"                    "Mapa Bolívar.gpkg"              
## [19] "Mapa Bolívar.gpkg.aux.xml"       "Municipios de Blvr.gpkg"        
## [21] "Municipios de Bolívar.gpkg"      "Municipios_9377.gpkg"           
## [23] "propiedades de municipios.gpkg"
colombia2 <- st_read("./Bolivar_municipios.gpkg")
## Multiple layers are present in data source C:\Users\imthe\Documents\GB2\Proyecto1\Datos\Bolivar_municipios.gpkg, reading layer `col_adm2'.
## Use `st_layers' to list all layer names and their type in a data source.
## Set the `layer' argument in `st_read' to read a particular layer.
## Warning in CPL_read_ogr(dsn, layer, query, as.character(options), quiet, :
## automatically selected the first layer in a data source containing more than
## one.
## Reading layer `col_adm2' from data source 
##   `C:\Users\imthe\Documents\GB2\Proyecto1\Datos\Bolivar_municipios.gpkg' 
##   using driver `GPKG'
## Simple feature collection with 36 features and 12 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -75.79764 ymin: 6.979202 xmax: -73.769 ymax: 10.80153
## Geodetic CRS:  WGS 84
unique(colombia$dpto_cnmbr)
##  [1] "ANTIOQUIA"                                               
##  [2] "ATLÁNTICO"                                               
##  [3] "BOGOTÁ, D.C."                                            
##  [4] "BOLÍVAR"                                                 
##  [5] "BOYACÁ"                                                  
##  [6] "CALDAS"                                                  
##  [7] "CAQUETÁ"                                                 
##  [8] "CAUCA"                                                   
##  [9] "CESAR"                                                   
## [10] "CÓRDOBA"                                                 
## [11] "CUNDINAMARCA"                                            
## [12] "CHOCÓ"                                                   
## [13] "HUILA"                                                   
## [14] "LA GUAJIRA"                                              
## [15] "MAGDALENA"                                               
## [16] "META"                                                    
## [17] "NARIÑO"                                                  
## [18] "NORTE DE SANTANDER"                                      
## [19] "QUINDÍO"                                                 
## [20] "RISARALDA"                                               
## [21] "SANTANDER"                                               
## [22] "SUCRE"                                                   
## [23] "TOLIMA"                                                  
## [24] "VALLE DEL CAUCA"                                         
## [25] "ARAUCA"                                                  
## [26] "CASANARE"                                                
## [27] "PUTUMAYO"                                                
## [28] "ARCHIPIÉLAGO DE SAN ANDRÉS, PROVIDENCIA Y SANTA CATALINA"
## [29] "AMAZONAS"                                                
## [30] "GUAINÍA"                                                 
## [31] "GUAVIARE"                                                
## [32] "VAUPÉS"                                                  
## [33] "VICHADA"

##Selección de entidades

Selección por atributo

(bolivar <- dplyr:: filter (colombia, dpto_cnmbr == "BOLÍVAR"))
head(bolivar)
nrow(bolivar)
## [1] 46
library(sf)
plot(st_geometry(bolivar), col = sf.colors(12, categorical = TRUE), border = 'grey', axes = TRUE)
plot(st_geometry(st_centroid(bolivar)), pch = 3, col = 'red', add = TRUE)
## Warning: st_centroid assumes attributes are constant over geometries

st_write(bolivar, "Municipios de Blvr.gpkg", driver = "GPKG", append = F)
## Deleting layer `Municipios de Blvr' using driver `GPKG'
## Writing layer `Municipios de Blvr' to data source 
##   `Municipios de Blvr.gpkg' using driver `GPKG'
## Writing 46 features with 11 fields and geometry type Multi Polygon.

Selección por locación

library(sf)
library(dplyr)
cities = read.csv('./World _Cities/worldcities.csv') %>% 
st_as_sf(coords=c("lng","lat"), crs=4326)
cities
st_crs(cities) $epsg
## [1] 4326
st_crs(bolivar) $epsg
## [1] 4326
ncities <- st_transform(cities, crs = st_crs(bolivar))
blvar_cities <- ncities [bolivar, , op = st_within]
plot(st_geometry(bolivar), col = sf.colors(12, categorical = TRUE), border = "grey", axes = TRUE)
plot(st_geometry(blvar_cities), pch = 20, col = "red", add = TRUE)

##Trazado del mapa

Trazado del mapa con ggplot

library(ggplot2)
ggplot() +
  geom_sf( data = bolivar) +
  geom_sf(data = blvar_cities, aes(color = city), size = 3)

  labs (x = "longitud", y = "latitud", title = "Ciudades de Bolívar") +
  theme_bw()
## NULL

Trazado usando ggplot y ggspatial

ggplot() + 
  geom_sf(data = bolivar) +
  geom_sf(data = blvar_cities, aes(color = city, label = city), size =3) +
  annotation_scale(location = "tr", height = unit(.25, "cm"),
                   width = unit(1, "cm"), pad_x = unit(0.3, "in"),
                   pad_y = unit(0.5, "in")) +
  annotation_north_arrow (height = unit(1, "cm"), width = unit(1, "cm"),
                          which_north = "true", location = "tr",
                          pad_x = unit(0.5, "in"), pad_y = unit(0.05, "in")) +
  labs (x = "Longitud", y = "Latitud" , title = "Ciudades de Bolívar") +
  theme_bw()
## Warning in layer_sf(geom = GeomSf, data = data, mapping = mapping, stat = stat,
## : Ignoring unknown aesthetics: label
## Warning in annotation_scale(location = "tr", height = unit(0.25, "cm"), :
## Ignoring unknown parameters: `width`

##Entorno Informático

sessionInfo()
## R version 4.6.0 (2026-04-24 ucrt)
## Platform: x86_64-w64-mingw32/x64
## Running under: Windows 11 x64 (build 26200)
## 
## Matrix products: default
##   LAPACK version 3.12.1
## 
## 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] ggspatial_1.1.10 ggplot2_4.0.3    dplyr_1.2.1      sf_1.1-1        
## 
## loaded via a namespace (and not attached):
##  [1] gtable_0.3.6       jsonlite_2.0.0     compiler_4.6.0     tidyselect_1.2.1  
##  [5] Rcpp_1.1.1-1.1     jquerylib_0.1.4    scales_1.4.0       yaml_2.3.12       
##  [9] fastmap_1.2.0      R6_2.6.1           generics_0.1.4     classInt_0.4-11   
## [13] s2_1.1.9           knitr_1.51         tibble_3.3.1       units_1.0-1       
## [17] DBI_1.3.0          bslib_0.10.0       pillar_1.11.1      RColorBrewer_1.1-3
## [21] rlang_1.2.0        cachem_1.1.0       xfun_0.57          sass_0.4.10       
## [25] S7_0.2.2           cli_3.6.6          withr_3.0.2        magrittr_2.0.5    
## [29] wk_0.9.5           class_7.3-23       digest_0.6.39      grid_4.6.0        
## [33] rstudioapi_0.18.0  lifecycle_1.0.5    vctrs_0.7.3        KernSmooth_2.23-26
## [37] proxy_0.4-29       evaluate_1.0.5     glue_1.8.1         farver_2.1.2      
## [41] e1071_1.7-17       rmarkdown_2.31     tools_4.6.0        pkgconfig_2.0.3   
## [45] htmltools_0.5.9