Taller 1: Primeros pasos en R

Author

Valerie Cortes

1 R como calculadora

Lo más sencillo que R puede hacer es calcular.

2 + 3
[1] 5
10 / 4
[1] 2.5
getwd()
[1] "D:/universidad/geomatica_R/taller1_geomatica/Taller1_geomatica.qmd"

2 Parte A

2.1 R como calculadora

2+3
[1] 5
10-4
[1] 6
6*7
[1] 42
10/4
[1] 2.5
2^3    # potencia: 2 elevado a 3
[1] 8
sqrt(16)  # raíz cuadrada
[1] 4
2+3*4   # primero multplica
[1] 14
(2+3)*4  # primero suma
[1] 20
150*80   # área de lote en metros cuadrados 150 m largo y 80 m ancho
[1] 12000
(150*80)/10000  # área de lote en hectáreas
[1] 1.2

2.2 Variables:guardar valores con un nombre

largo=150
ancho=80
largo
[1] 150
area_m2=largo*ancho
area_ha=area_m2/10000
area_ha
[1] 1.2

El orden importa

largo=200
area_ha   #area_ha continua igual tendrias que actualizarla para que cambie
[1] 1.2
area_m2=largo*ancho
area_m2
[1] 16000
rendimiento=22  # toneladas por hectarea
rendimiento
[1] 22
produccion_t=rendimiento*area_ha
produccion_t  #produccion total del lote con 1.6 hectareas
[1] 26.4

2.3 Tipos de datos

cultivo="papa"
class(cultivo)
[1] "character"
class(area_ha)
[1] "numeric"
class(TRUE)
[1] "logical"

Comparaciones producen valores logicos

area_ha>1  #¿El lote tiene más de 1 ha?
[1] TRUE
cultivo=="papa"  #¿El cultivo es papa? (Los 2 signos igual con para comparar)
[1] TRUE
cultivo!="maiz"  #¿El cultivo es distinto de maíz?
[1] TRUE

2.4 Vectores: muchos valores juntos

rendimiento=c(18.5, 22.1, 15.3, 25.0, 19.8)  # Vector de Rendimiento de papa (t/ha) en cinco lotes de una finca
rendimiento
[1] 18.5 22.1 15.3 25.0 19.8
length(rendimiento)  # Cuantos valores hay en el vector
[1] 5
mean(rendimiento)  # promedio
[1] 20.14
max(rendimiento)  # Máximo
[1] 25
min(rendimiento)  # Mínimo
[1] 15.3
sum(rendimiento)  # Suma
[1] 100.7
rendimiento*1000  # Pasar de t/ha a kg/ha (estos se aplica a todos los lotes)
[1] 18500 22100 15300 25000 19800

Sacar elementos de un vector

rendimiento[2]  # Los [] indican la posición del elemento (en este caso el segundo)
[1] 22.1
rendimiento[c(1,3)]  # El primero y el tercero
[1] 18.5 15.3

Filtrar con condiciones

rendimiento>20
[1] FALSE  TRUE FALSE  TRUE FALSE
rendimiento[rendimiento>20]  #Entre corchetes R solo da los TRUE
[1] 22.1 25.0
#Vector lluvia_mm con precipitacion de 6 meses
lluvia_mm=c(120, 85, 210, 160, 45, 98)
length(lluvia_mm)
[1] 6
mean(lluvia_mm)
[1] 119.6667
lluvia_mm<100
[1] FALSE  TRUE FALSE FALSE  TRUE  TRUE
lluvia_mm[lluvia_mm<100]
[1] 85 45 98
sum(lluvia_mm<100)
[1] 3

2.5 Funciones: usar y crear

promedio <- mean(rendimiento)
promedio
[1] 20.14
round(promedio, digits = 1)  # redondear a 1 decimal
[1] 20.1

Pedir ayuda

# El signo "?" + nombre le indica en el panel Help le indica su función 

Crear sus propias funciones

m2_a_ha=function(m2){
  m2/10000
}
m2_a_ha(12000)
[1] 1.2
m2_a_ha(c(5000, 25000, 80000))  # ¡también funciona con vectores!
[1] 0.5 2.5 8.0

Ejercicio

produccion=function(area_ha, rendimiento_t_ha){
  resultado=area_ha*rendimiento_t_ha
  return(resultado)
}
produccion(3.5, 20)
[1] 70

2.6 Tablas de datos (data frames)

lotes <- data.frame(
  lote        = c("A", "B", "C", "D", "E", "F"),
  cultivo     = c("papa", "papa", "maiz", "cafe", "maiz", "papa"),
  area_ha     = c(2.5, 1.8, 4.0, 3.2, 2.0, 1.2),
  rendimiento = c(18.5, 22.1, 5.3, 1.9, 6.1, 25.0)  # t/ha
)
lotes
  lote cultivo area_ha rendimiento
1    A    papa     2.5        18.5
2    B    papa     1.8        22.1
3    C    maiz     4.0         5.3
4    D    cafe     3.2         1.9
5    E    maiz     2.0         6.1
6    F    papa     1.2        25.0

Explorar la tabla

nrow(lotes)  # Número de filas
[1] 6
ncol(lotes)  # Numero de columnas
[1] 4
names(lotes)  # Nombres de las columnas
[1] "lote"        "cultivo"     "area_ha"     "rendimiento"
str(lotes)  # Estructura:tipo de cada columna
'data.frame':   6 obs. of  4 variables:
 $ lote       : chr  "A" "B" "C" "D" ...
 $ cultivo    : chr  "papa" "papa" "maiz" "cafe" ...
 $ area_ha    : num  2.5 1.8 4 3.2 2 1.2
 $ rendimiento: num  18.5 22.1 5.3 1.9 6.1 25

Trabajar con una columna: el signo $

lotes$area_ha
[1] 2.5 1.8 4.0 3.2 2.0 1.2
sum(lotes$area_ha)   # área total de la finca
[1] 14.7
lotes$produccion_t <- lotes$area_ha * lotes$rendimiento  # Crear una columna nueva es asignarle un valor
lotes
  lote cultivo area_ha rendimiento produccion_t
1    A    papa     2.5        18.5        46.25
2    B    papa     1.8        22.1        39.78
3    C    maiz     4.0         5.3        21.20
4    D    cafe     3.2         1.9         6.08
5    E    maiz     2.0         6.1        12.20
6    F    papa     1.2        25.0        30.00

Flitrar fila

lotes[lotes$cultivo == "papa", ]  # En la tabla los corchetes van en dos partes [filas, columnas], si se deja vacio despues de la coma R lo toma como todad las columnas.
  lote cultivo area_ha rendimiento produccion_t
1    A    papa     2.5        18.5        46.25
2    B    papa     1.8        22.1        39.78
6    F    papa     1.2        25.0        30.00

Paquete dplyr

library(dplyr)
Warning: package 'dplyr' was built under R version 4.6.1

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
lotes|>filter(cultivo == "papa") #|> se llama pipe (tubería). Léalo como “y luego”: “tome lotes y luego filtre los de papa”. Atajo: Ctrl + Shift + M. Permite encadenar pasos:
  lote cultivo area_ha rendimiento produccion_t
1    A    papa     2.5        18.5        46.25
2    B    papa     1.8        22.1        39.78
3    F    papa     1.2        25.0        30.00
lotes |>
  filter(cultivo == "papa") |>
  arrange(desc(produccion_t))   # ordenar de mayor a menor producción
  lote cultivo area_ha rendimiento produccion_t
1    A    papa     2.5        18.5        46.25
2    B    papa     1.8        22.1        39.78
3    F    papa     1.2        25.0        30.00

Ejercicio

lotes |>
  filter(area_ha > 2)
  lote cultivo area_ha rendimiento produccion_t
1    A    papa     2.5        18.5        46.25
2    C    maiz     4.0         5.3        21.20
3    D    cafe     3.2         1.9         6.08
lotes|>
  filter(cultivo == "maiz",) |>
           select(lote,
                  produccion_t)
  lote produccion_t
1    C         21.2
2    E         12.2
lotes |>
  group_by(cultivo) |>
  summarise(produccion_total = sum(produccion_t)) |>
  arrange(desc(produccion_total))
# A tibble: 3 × 2
  cultivo produccion_total
  <chr>              <dbl>
1 papa              116.  
2 maiz               33.4 
3 cafe                6.08

cultivo con mayor producción total en la finca es papa (116.03)

2.7 Leer los errores (y no asustarse)

chunks con errores

rendimeinto
Error:
! objeto 'rendimeinto' no encontrado

solución : mala escritura

rendimiento
[1] 18.5 22.1 15.3 25.0 19.8
Mean(rendimiento)
Error in `Mean()`:
! no se pudo encontrar la función "Mean"

mal comando

mean(rendimiento)
[1] 20.14
c(1, 2 3)  
Error in parse(text = input): <text>:1:8: unexpected numeric constant
1: c(1, 2 3
           ^

falta una coma

c(1, 2,3)  
[1] 1 2 3
"papa" * 2   
Error in `"papa" * 2`:
! argumento no-numérico para operador binario

Nota: “papa” con es un operador numerico por lo cual no se pueden realizar operaciones con el

paquetes <- c("sf", "dplyr")
faltan <- setdiff(paquetes, rownames(installed.packages()))
if (length(faltan) > 0) install.packages(faltan)

Parte B Apliccación: datos espaciales con sf # Leer una capa de municipios sf (simple features) permite trabajar con datos vectoriales (puntos, líneas, polígonos), igual que en QGIS.

library(sf)
Warning: package 'sf' was built under R version 4.6.2
Linking to GEOS 3.14.1, GDAL 3.12.1, PROJ 9.7.1; sf_use_s2() is TRUE
library(dplyr)
ruta_shp <- "D:/universidad/geomatica_R/taller1_geomatica/datos/mun_santander_boyaca.shp"

municipios <- st_read(ruta_shp)
Reading layer `mun_santander_boyaca' from data source 
  `D:\universidad\geomatica_R\taller1_geomatica\datos\mun_santander_boyaca.shp' 
  using driver `ESRI Shapefile'
Simple feature collection with 210 features and 90 fields
Geometry type: POLYGON
Dimension:     XY
Bounding box:  xmin: -74.66496 ymin: 4.655196 xmax: -71.94885 ymax: 8.14501
Geodetic CRS:  MAGNA-SIRGAS

municipios: 210 atributos: 90 geometria: poligonos CRS: MAGNA-SIRGAS Un objeto sf es una tabla con mapa

class(municipios)
[1] "sf"         "data.frame"

municipios es a la vez sf y data.frame. Es decir: es una tabla como lotes, con una columna especial llamada geometry donde está la forma de cada municipio. Por eso todo lo que aprendió en la Parte A funciona aquí:

nrow(municipios)
[1] 210
names(municipios) # Nombres de los municipios
 [1] "DPTO_CCDGO" "MPIO_CCDGO" "MPIO_CNMBR" "MPIO_CDPMP" "VERSION"   
 [6] "AREA"       "LATITUD"    "LONGITUD"   "STCTNENCUE" "STP3_1_SI" 
[11] "STP3_2_NO"  "STP3A_RI"   "STP3B_TCN"  "STP4_1_SI"  "STP4_2_NO" 
[16] "STP9_1_USO" "STP9_2_USO" "STP9_3_USO" "STP9_4_USO" "STP9_2_1_M"
[21] "STP9_2_2_M" "STP9_2_3_M" "STP9_2_4_M" "STP9_2_9_M" "STP9_3_1_N"
[26] "STP9_3_2_N" "STP9_3_3_N" "STP9_3_4_N" "STP9_3_5_N" "STP9_3_6_N"
[31] "STP9_3_7_N" "STP9_3_8_N" "STP9_3_9_N" "STP9_3_10"  "STP9_3_99" 
[36] "STVIVIENDA" "STP14_1_TI" "STP14_2_TI" "STP14_3_TI" "STP14_4_TI"
[41] "STP14_5_TI" "STP14_6_TI" "STP15_1_OC" "STP15_2_OC" "STP15_3_OC"
[46] "STP15_4_OC" "TSP16_HOG"  "STP19_EC_1" "STP19_ES_2" "STP19_EE_1"
[51] "STP19_EE_2" "STP19_EE_3" "STP19_EE_4" "STP19_EE_5" "STP19_EE_6"
[56] "STP19_EE_9" "STP19_ACU1" "STP19_ACU2" "STP19_ALC1" "STP19_ALC2"
[61] "STP19_GAS1" "STP19_GAS2" "STP19_GAS9" "STP19_REC1" "STP19_REC2"
[66] "STP19_INT1" "STP19_INT2" "STP19_INT9" "STP27_PERS" "STPERSON_L"
[71] "STPERSON_S" "STP32_1_SE" "STP32_2_SE" "STP34_1_ED" "STP34_2_ED"
[76] "STP34_3_ED" "STP34_4_ED" "STP34_5_ED" "STP34_6_ED" "STP34_7_ED"
[81] "STP34_8_ED" "STP34_9_ED" "STP51_PRIM" "STP51_SECU" "STP51_SUPE"
[86] "STP51_POST" "STP51_13_E" "STP51_99_E" "Shape_Leng" "Shape_Area"
[91] "geometry"  

Tabla sin geometría

municipios |>
  st_drop_geometry() |>
  select(DPTO_CCDGO, MPIO_CCDGO, MPIO_CNMBR, STP27_PERS) |>
  head()
  DPTO_CCDGO MPIO_CCDGO MPIO_CNMBR STP27_PERS
1         15        001      TUNJA     167991
2         15        022    ALMEIDA       1582
3         15        047  AQUITANIA      13860
4         15        051   ARCABUCO       5465
5         15        087      BELÉN       7322
6         15        090     BERBEO       1453

Nota:Las columnas que empiezan por STP vienen del Censo Nacional de Población y Vivienda 2018 del DANE. Por ejemplo, STP27_PERS es el total de personas del municipio. Consulte el diccionario de datos del DANE para el significado de las demás. Su primer mapa

plot(st_geometry(municipios)) # Plot dibuja la capa y st_geometry dibuja los contornos

plot(municipios["DPTO_CCDGO"]) #los corchetes colorea el mapa segun el valor 

plot(municipios["STP27_PERS"], main = "Población total (Censo 2018)")

Ejercicio Haga un mapa con otra columna de la tabla y póngale un título con main = “…”.

plot(municipios["MPIO_CCDGO"], main = "...")

2.8 Sistema de coordenada y reproyección

st_crs(municipios)$epsg # Para mira el CRS de los datos 
[1] 4686
st_bbox(municipios)
      xmin       ymin       xmax       ymax 
-74.664960   4.655196 -71.948854   8.145010 

Datos MAGNA-SIRGAS geográficas (EPSG 4686) las coordenada son en grados para reproyectar

municipios_9377 <- st_transform(municipios, 9377)
st_crs(municipios_9377)$epsg
[1] 9377
st_bbox(municipios_9377)
   xmin    ymin    xmax    ymax 
4815712 2072396 5116057 2458100 
st_crs(municipios_9377)
Coordinate Reference System:
  User input: EPSG:9377 
  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]]

se reproyecto el CRS a 9377 y este muestra las coordenada en metros ## Calcular nuevos atributos

municipios_9377$area_km2 = as.numeric(st_area(municipios_9377)) / 1000000

se creo una columna nueva a partir de otras como en lotes$producción_t Densidad de población

municipios_9377$densidad = municipios_9377$STP27_PERS / municipios_9377$area_km2

municipios_9377 |>
  st_drop_geometry() |>
  select(MPIO_CNMBR, STP27_PERS, area_km2, densidad) |>
  arrange(desc(densidad)) |>
  head(5)
     MPIO_CNMBR STP27_PERS  area_km2  densidad
1   BUCARAMANGA     528855 152.62869 3464.9776
2 FLORIDABLANCA     275109 100.13660 2747.3373
3         TUNJA     167991 119.48492 1405.9599
4       BARBOSA      28769  46.59283  617.4555
5      SOGAMOSO     120462 207.88393  579.4676
plot(municipios_9377["densidad"],
     breaks = "quantile",
     main = "Densidad de población (hab/km²)")

2.9 Seleccionar municipios

Por departamento

class(municipios_9377$DPTO_CCDGO)
[1] "character"
unique(municipios_9377$DPTO_CCDGO)
[1] "15" "68"

en esta c pa solo hay 2 departamentos y los codigos son tipo texto

boyaca = municipios_9377 |>
  filter(DPTO_CCDGO == "15")

nrow(boyaca)
[1] 123
plot(st_geometry(boyaca), main = "Municipios de Boyacá")

Ejercicio ¿Qué pasaría si filtrara con un código que no está en la capa, por ejemplo “18”? Pruébelo y mire con nrow() cuántas filas quedan. ¿Le daría R un error, o algo más difícil de detectar?

 municipios_9377 |>
  filter(DPTO_CCDGO == "18")
Simple feature collection with 0 features and 92 fields
Geometry type: POLYGON
Bounding box:  xmin: NA ymin: NA xmax: NA ymax: NA
Projected CRS: MAGNA-SIRGAS 2018 / Origen-Nacional
 [1] DPTO_CCDGO MPIO_CCDGO MPIO_CNMBR MPIO_CDPMP VERSION    AREA      
 [7] LATITUD    LONGITUD   STCTNENCUE STP3_1_SI  STP3_2_NO  STP3A_RI  
[13] STP3B_TCN  STP4_1_SI  STP4_2_NO  STP9_1_USO STP9_2_USO STP9_3_USO
[19] STP9_4_USO STP9_2_1_M STP9_2_2_M STP9_2_3_M STP9_2_4_M STP9_2_9_M
[25] STP9_3_1_N STP9_3_2_N STP9_3_3_N STP9_3_4_N STP9_3_5_N STP9_3_6_N
[31] STP9_3_7_N STP9_3_8_N STP9_3_9_N STP9_3_10  STP9_3_99  STVIVIENDA
[37] STP14_1_TI STP14_2_TI STP14_3_TI STP14_4_TI STP14_5_TI STP14_6_TI
[43] STP15_1_OC STP15_2_OC STP15_3_OC STP15_4_OC TSP16_HOG  STP19_EC_1
[49] STP19_ES_2 STP19_EE_1 STP19_EE_2 STP19_EE_3 STP19_EE_4 STP19_EE_5
[55] STP19_EE_6 STP19_EE_9 STP19_ACU1 STP19_ACU2 STP19_ALC1 STP19_ALC2
[61] STP19_GAS1 STP19_GAS2 STP19_GAS9 STP19_REC1 STP19_REC2 STP19_INT1
[67] STP19_INT2 STP19_INT9 STP27_PERS STPERSON_L STPERSON_S STP32_1_SE
[73] STP32_2_SE STP34_1_ED STP34_2_ED STP34_3_ED STP34_4_ED STP34_5_ED
[79] STP34_6_ED STP34_7_ED STP34_8_ED STP34_9_ED STP51_PRIM STP51_SECU
[85] STP51_SUPE STP51_POST STP51_13_E STP51_99_E Shape_Leng Shape_Area
[91] geometry   area_km2   densidad  
<0 rows> (o 0- extensión row.names)
nrow(18)
NULL

no hay municipios con ese codigo y las filas que quedan no hay NULL Por condición

grandes <- municipios_9377 |>
  filter(area_km2 > 1000)

grandes |> st_drop_geometry() |> select(MPIO_CNMBR, area_km2)
              MPIO_CNMBR area_km2
1          PUERTO BOYACÁ 1512.084
2                 CUBARÁ 1174.692
3        BARRANCABERMEJA 1324.926
4              CIMITARRA 3170.518
5               RIONEGRO 1166.437
6       SABANA DE TORRES 1400.656
7 SAN VICENTE DE CHUCURÍ 1114.575
8         PUERTO WILCHES 1505.814
9                BOLÍVAR 1008.889

Ejercicio Cree un objeto santander con solo los municipios de Santander y dibújelo. ¿Cuántos municipios de Santander tienen más de 50 000 habitantes? Muestre sus nombres. Dibuje el mapa de densidad solo para Santander.

santander = municipios_9377 |>
  filter(DPTO_CCDGO == "68")
plot(st_geometry(santander))

names(municipios_9377)
 [1] "DPTO_CCDGO" "MPIO_CCDGO" "MPIO_CNMBR" "MPIO_CDPMP" "VERSION"   
 [6] "AREA"       "LATITUD"    "LONGITUD"   "STCTNENCUE" "STP3_1_SI" 
[11] "STP3_2_NO"  "STP3A_RI"   "STP3B_TCN"  "STP4_1_SI"  "STP4_2_NO" 
[16] "STP9_1_USO" "STP9_2_USO" "STP9_3_USO" "STP9_4_USO" "STP9_2_1_M"
[21] "STP9_2_2_M" "STP9_2_3_M" "STP9_2_4_M" "STP9_2_9_M" "STP9_3_1_N"
[26] "STP9_3_2_N" "STP9_3_3_N" "STP9_3_4_N" "STP9_3_5_N" "STP9_3_6_N"
[31] "STP9_3_7_N" "STP9_3_8_N" "STP9_3_9_N" "STP9_3_10"  "STP9_3_99" 
[36] "STVIVIENDA" "STP14_1_TI" "STP14_2_TI" "STP14_3_TI" "STP14_4_TI"
[41] "STP14_5_TI" "STP14_6_TI" "STP15_1_OC" "STP15_2_OC" "STP15_3_OC"
[46] "STP15_4_OC" "TSP16_HOG"  "STP19_EC_1" "STP19_ES_2" "STP19_EE_1"
[51] "STP19_EE_2" "STP19_EE_3" "STP19_EE_4" "STP19_EE_5" "STP19_EE_6"
[56] "STP19_EE_9" "STP19_ACU1" "STP19_ACU2" "STP19_ALC1" "STP19_ALC2"
[61] "STP19_GAS1" "STP19_GAS2" "STP19_GAS9" "STP19_REC1" "STP19_REC2"
[66] "STP19_INT1" "STP19_INT2" "STP19_INT9" "STP27_PERS" "STPERSON_L"
[71] "STPERSON_S" "STP32_1_SE" "STP32_2_SE" "STP34_1_ED" "STP34_2_ED"
[76] "STP34_3_ED" "STP34_4_ED" "STP34_5_ED" "STP34_6_ED" "STP34_7_ED"
[81] "STP34_8_ED" "STP34_9_ED" "STP51_PRIM" "STP51_SECU" "STP51_SUPE"
[86] "STP51_POST" "STP51_13_E" "STP51_99_E" "Shape_Leng" "Shape_Area"
[91] "geometry"   "area_km2"   "densidad"  
mayores_50000 <- santander |>
  filter(densidad > 50000)
nrow(mayores_50000)
[1] 0
mayores_50000 |>
  st_drop_geometry() |>
  select(MPIO_CNMBR, densidad)
[1] MPIO_CNMBR densidad  
<0 rows> (o 0- extensión row.names)
santander <- santander |>
  mutate(densidad = densidad / area_km2)
library(ggplot2)

ggplot(santander) +
  geom_sf(aes(fill = densidad)) +
  scale_fill_viridis_c(name = "Habitantes por km²") +
  labs(title = "Densidad poblacional de Santander") +
  theme_minimal()

2.10 Guardad resultados

dir.create("salidas", showWarnings = FALSE)   # crea la carpeta si no existe

st_write(municipios_9377, "salidas/municipios_9377.gpkg", delete_dsn = TRUE)
Deleting source `salidas/municipios_9377.gpkg' using driver `GPKG'
Writing layer `municipios_9377' to data source 
  `salidas/municipios_9377.gpkg' using driver `GPKG'
Writing 210 features with 92 fields and geometry type Polygon.
st_write(boyaca, "salidas/boyaca_9377.gpkg", delete_dsn = TRUE)
Deleting source `salidas/boyaca_9377.gpkg' using driver `GPKG'
Writing layer `boyaca_9377' to data source 
  `salidas/boyaca_9377.gpkg' using driver `GPKG'
Writing 123 features with 92 fields and geometry type Polygon.

para verificar que aparescan

list.files("salidas")
[1] "boyaca_9377.gpkg"     "municipios_9377.gpkg" "reto_boyaca.gpkg"    
[4] "santander_9377.gpkg" 

Si aparecen ahora verificar que abren

test <- st_read("salidas/municipios_9377.gpkg")
Reading layer `municipios_9377' from data source 
  `D:\universidad\geomatica_R\taller1_geomatica\Taller1_geomatica.qmd\salidas\municipios_9377.gpkg' 
  using driver `GPKG'
Simple feature collection with 210 features and 92 fields
Geometry type: POLYGON
Dimension:     XY
Bounding box:  xmin: 4815712 ymin: 2072396 xmax: 5116057 ymax: 2458100
Projected CRS: MAGNA-SIRGAS 2018 / Origen-Nacional

Ahora para santander

st_write(santander, "salidas/santander_9377.gpkg", delete_dsn = TRUE)
Deleting source `salidas/santander_9377.gpkg' using driver `GPKG'
Writing layer `santander_9377' to data source 
  `salidas/santander_9377.gpkg' using driver `GPKG'
Writing 87 features with 92 fields and geometry type Polygon.

2.11 Verificar en Qgis

al abris el shp en Qgis se suben las capas con los CRS correctos y en la tabla de atributos aparecen las columnas añadidas en R ## Reto final

boyaca <- municipios_9377 |>
  filter(as.character(DPTO_CCDGO) == "15")
boyaca |>
  st_drop_geometry() |>
  select(MPIO_CNMBR, DPTO_CCDGO)
               MPIO_CNMBR DPTO_CCDGO
1                   TUNJA         15
2                 ALMEIDA         15
3               AQUITANIA         15
4                ARCABUCO         15
5                   BELÉN         15
6                  BERBEO         15
7               BETÉITIVA         15
8                 BOAVITA         15
9                  BOYACÁ         15
10                BRICEÑO         15
11             BUENAVISTA         15
12               BUSBANZÁ         15
13                 CALDAS         15
14           CAMPOHERMOSO         15
15                CERINZA         15
16              CHINAVITA         15
17           CHIQUINQUIRÁ         15
18                  CHITA         15
19             CHITARAQUE         15
20                CHIVATÁ         15
21                CIÉNEGA         15
22                CÓMBITA         15
23                  COPER         15
24               CORRALES         15
25         LABRANZAGRANDE         15
26             LA CAPILLA         15
27            LA VICTORIA         15
28               LA UVITA         15
29                  PESCA         15
30                  PISBA         15
31          PUERTO BOYACÁ         15
32                QUÍPAMA         15
33                 SOCOTÁ         15
34                  SOCHA         15
35               SOGAMOSO         15
36              SOMONDOCO         15
37                 ÚMBITA         15
38           VENTAQUEMADA         15
39              VIRACACHÁ         15
40              ZETAQUIRA         15
41             COVARACHÍA         15
42                CUCAITA         15
43                CUÍTIVA         15
44               CHÍQUIZA         15
45                 CHIVOR         15
46                DUITAMA         15
47               EL COCUY         15
48              EL ESPINO         15
49             FIRAVITOBA         15
50               FLORESTA         15
51             GACHANTIVÁ         15
52                 GÁMEZA         15
53                GARAGOA         15
54             GUACAMAYAS         15
55               GUATEQUE         15
56                GUAYATÁ         15
57                    IZA         15
58               JENESANO         15
59                 JERICÓ         15
60         VILLA DE LEYVA         15
61                MACANAL         15
62                 MARIPÍ         15
63             MIRAFLORES         15
64                 MONGUA         15
65                 MONGUÍ         15
66              MONIQUIRÁ         15
67               MOTAVITA         15
68                   MUZO         15
69                  NOBSA         15
70            NUEVO COLÓN         15
71                 OICATÁ         15
72                OTANCHE         15
73              PACHAVITA         15
74                   PÁEZ         15
75                  PAIPA         15
76               PAJARITO         15
77               PANQUEBA         15
78                  PAUNA         15
79                   PAYA         15
80             PAZ DE RÍO         15
81              RAMIRIQUÍ         15
82                RÁQUIRA         15
83                 RONDÓN         15
84                 SABOYÁ         15
85                SÁCHICA         15
86                 SAMACÁ         15
87            SAN EDUARDO         15
88       SAN JOSÉ DE PARE         15
89     SAN LUIS DE GACENO         15
90              SAN MATEO         15
91     SAN MIGUEL DE SEMA         15
92    SAN PABLO DE BORBUR         15
93                SANTANA         15
94            SANTA MARÍA         15
95  SANTA ROSA DE VITERBO         15
96            SANTA SOFÍA         15
97            SATIVANORTE         15
98              SATIVASUR         15
99              SIACHOQUE         15
100                 SOATÁ         15
101                  SORA         15
102             SOTAQUIRÁ         15
103                SORACÁ         15
104               SUSACÓN         15
105           SUTAMARCHÁN         15
106             SUTATENZA         15
107                 TASCO         15
108                 TENZA         15
109                TIBANÁ         15
110              TIBASOSA         15
111               TINJACÁ         15
112             TIPACOQUE         15
113                  TOCA         15
114                 TOGÜÍ         15
115                TÓPAGA         15
116                  TOTA         15
117              TUNUNGUÁ         15
118              TURMEQUÉ         15
119                  TUTA         15
120                TUTAZÁ         15
121               CHISCAS         15
122                CUBARÁ         15
123   GÜICÁN DE LA SIERRA         15
km2_a_ha = function(km2) {
  km2 * 100
}
km2_a_ha(10)
[1] 1000
boyaca =boyaca |>
  mutate(area_ha = km2_a_ha(area_km2)) # mutate para crear una nueva columna
km2_a_ha = function(km2) {
  km2 * 100
}
boyaca = boyaca |>
  mutate(area_ha = km2_a_ha(area_km2))
top5_boyaca = boyaca |>
  arrange(desc(area_km2)) |>
  slice_head(n = 5)
top5_boyaca |>
  st_drop_geometry() |>
  select(MPIO_CNMBR, area_km2, area_ha)
           MPIO_CNMBR  area_km2   area_ha
1       PUERTO BOYACÁ 1512.0837 151208.37
2              CUBARÁ 1174.6921 117469.21
3 GÜICÁN DE LA SIERRA  949.8998  94989.98
4           AQUITANIA  940.2288  94022.88
5               CHITA  675.8078  67580.78
library(ggplot2)

ggplot(boyaca) +
  geom_sf(aes(fill = STP27_PERS)) +
  scale_fill_viridis_c(name = "Población") +
  labs(title = "Población de los municipios de Boyacá") +
  theme_minimal()

st_write(
  boyaca,
  "salidas/reto_boyaca.gpkg",
  delete_dsn = TRUE
)
Deleting source `salidas/reto_boyaca.gpkg' using driver `GPKG'
Writing layer `reto_boyaca' to data source 
  `salidas/reto_boyaca.gpkg' using driver `GPKG'
Writing 123 features with 93 fields and geometry type Polygon.