library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(sf)
## Linking to GEOS 3.11.2, GDAL 3.7.2, PROJ 9.3.0; sf_use_s2() is TRUE
library(ggplot2)
library(scales)
## 
## Attaching package: 'scales'
## 
## The following object is masked from 'package:purrr':
## 
##     discard
## 
## The following object is masked from 'package:readr':
## 
##     col_factor

##First task #Produce a map showing the centroids of each municipality in just the state of Sao Paulo and add the outer boundary of Sao Paolo State.

  1. Open municipalities and filter for SP State
municipalities <- read_sf("C:/Users/Adedeji.Dahunsi/Desktop/MSc Data Science/Data/municipalities.shp")

municipalities_SP <- municipalities %>% filter(UF=="SP")

#Print the selected data within the console

print(municipalities_SP[,])
## Simple feature collection with 659 features and 6 fields
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: -53.10469 ymin: -25.31024 xmax: -44.16113 ymax: -19.78558
## Geodetic CRS:  WGS 84
## # A tibble: 659 × 7
##    COD_MUN NOME          UF    POP_201 IDHM_10 PIB_PER                  geometry
##      <int> <chr>         <chr>   <dbl>   <dbl>   <dbl>             <POLYGON [°]>
##  1 3509908 CANANEIA      SP      12216   0.72     9201 ((-48.09754 -25.31023, -…
##  2 3509908 CANANEIA      SP      12216   0.72     9201 ((-47.91403 -25.16738, -…
##  3 3509908 CANANEIA      SP      12216   0.72     9201 ((-47.86343 -25.12852, -…
##  4 3505351 BARRA DO CHA… SP       5305   0.66     7305 ((-49.25004 -24.44493, -…
##  5 3522653 ITAPIRAPUA P… SP       3926   0.661    6822 ((-49.20744 -24.70042, -…
##  6 3523206 ITARARE       SP      48143   0.703   12292 ((-49.25389 -24.31763, -…
##  7 3507159 BOM SUCESSO … SP       3623   0.66     8507 ((-49.25192 -24.40347, -…
##  8 3554300 TEODORO SAMP… SP      21595   0.741   12599 ((-52.28946 -22.62776, -…
##  9 3504008 ASSIS         SP      96336   0.805   14272 ((-50.5712 -22.68999, -5…
## 10 3528809 MARACAI       SP      13382   0.771   32164 ((-50.5138 -22.6032, -50…
## # ℹ 649 more rows
  1. Generate municipalities centroids and plot them
municipalities_centroid <- municipalities_SP %>% st_centroid()

municipalities_centroid %>% ggplot() + geom_sf()

  1. Dissolve SP State Polygons to create SP State Border
SP_border <- municipalities_SP %>% st_union()
  1. Plot SP centroids and SP border together
SP_border %>% ggplot() + geom_sf() +
  geom_sf(data=municipalities_centroid) +
  theme_classic()

##Second task What is the mean Human Development Index of municipalities in each state of Brazil?

  1. Remember that HDI is a variable from municipalities data set. Open table to see it.

  2. Calculate mean HDI by state

br_states <- municipalities %>% group_by(UF) %>% summarize(IDHM_mean=mean(IDHM_10))
  1. Plot the result
br_states %>% ggplot() + 
  geom_sf(aes(fill=IDHM_mean)) +
  theme_classic() +
  scale_fill_continuous(low="red",high="green")

##Third Task Produce a polygon/shapefile mapping the area of the municipality ‘Gaucha do Norte’ that is in the indigenous territory “Parque do Xingu”.

  1. Import indigenous park shapefile and plot it
indigenous <- read_sf("C:/Users/Adedeji.Dahunsi/Desktop/MSc Data Science/Data/BC250_Terra_Indigena_A.shp") %>% st_transform(4326)

br_states%>% ggplot() +
  geom_sf() +
  geom_sf(data=indigenous, fill="red")

  1. Create a shapefile for Gaucha do Norte e Xingu
Xingu <- indigenous %>% filter(nome=="Parque do Xingu") %>% st_transform(4326)
Gaucha <- municipalities %>% filter(NOME=="GAUCHA DO NORTE") %>% st_transform(4326)
  1. Plot the shapefiles to see the overlap
Gaucha %>% ggplot() +
  geom_sf(fill="red") +
  geom_sf(data=Xingu, fill="blue", alpha=0.5)

  1. Create shapefile for intersection and plot it
intersection <- Gaucha %>% st_intersection(Xingu)
## Warning: attribute variables are assumed to be spatially constant throughout
## all geometries
intersection %>% ggplot() + geom_sf(fill="dark green")

  1. Next, we Plot all together
Gaucha %>% ggplot() +
  geom_sf(fill= "red", alpha = 0.5) +
  geom_sf(data = Xingu, fill = "blue", alpha = 0.5) +
  geom_sf(data = intersection, fill = "black")

You can calculate the intersection area, for example

  st_area(intersection)
## 8109249396 [m^2]

Fourth Task

In the state of Acre (AC), which two social housing (MCMV) projects are closest to each other? Create a 20km buffer around each housing project.

  1. Import housing shapefile
  Housing <- read_sf("C:/Users/Adedeji.Dahunsi/Desktop/MSc Data Science/Data/MCMV_new.shp")
  1. Select housing in AC state and plot the outcome
Housing_AC <- Housing %>% filter(UF=="AC") 
br_states %>% filter(UF=="AC") %>% ggplot() +
  geom_sf() +
  geom_sf(data = Housing_AC)

  1. Calculate distance between housing points and view result
distance <- Housing_AC %>%
  st_transform(29189) %>%
  st_distance() %>%
  as.data.frame()
  1. Generate Buffer around Housing Points
Housing_AC %>% st_transform(29189) %>%
  st_buffer(20000) %>%
  ggplot() + geom_sf(fill="dark green")

  1. Plot All Output Together
br_states %>% filter(UF=="AC") %>% ggplot() +
  geom_sf() +
  geom_sf(data = (Housing_AC %>% st_transform(29189) %>% st_buffer (20000)), fill = "dark green") +
            geom_sf(data = Housing_AC, color = "red")

Fifth Task

Across Brazil, indicate the municipality that has the highest number of MCMV housing units (UH) in its territory? Create a map of the distribution of total housing units by municipality

  1. Spatial join between municipalities and housing
mun_Housing_units <- municipalities %>% st_join(Housing)
  1. Calculate the total of Housing Units in each municipality
mun_Housing_units <- mun_Housing_units %>%
  group_by(COD_MUN,NOME) %>%
  summarize(UH=sum(UH,na.rm=TRUE)) %>%
  ungroup()
## `summarise()` has grouped output by 'COD_MUN'. You can override using the
## `.groups` argument.
  1. Select the municipality with most Housing Units
mun_Housing_units %>% arrange(-UH) %>% slice(1) %>% pull(NOME)
## [1] "RIO DE JANEIRO"

[1] “RIO DE JANEIRO”

  1. Plot the distribution of total housing units by municipality
mun_Housing_units %>% ggplot() +
  geom_sf(aes(fill=UH), col=NA) +
  scale_fill_gradient(low="#ccece6", high="dark green", trans = "log") +
  theme_classic()
## Warning: Transformation introduced infinite values in discrete y-axis

Extra Activities 1 - Create a voronoi polygon for SP State

  1. Load the required Libraries
library(deldir)
## deldir 2.0-2      Nickname: "Partial Distinction"
## 
##      The syntax of deldir() has changed since version 
##      0.0-10.  In particular the "dummy points" facility 
##      (which was a historical artifact) has been removed. 
##      In the current version, 1.0-8, an argument "id" has 
##      been added to deldir().  This new argument permits the 
##      user to specifier identifiers for points.  The default 
##      behaviour is to continue using the indices of the 
##      points to identify them.  In view of the fact that 
##      point identifiers may be user-supplied, the arguement 
##      "number", in plot.deldir() and plot.tile.list(), has 
##      had its name changed to "labelPts", and the argument 
##      "nex" in plot.deldir() has had its name changed to 
##      "lex".  In addition the name of the forth component 
##      of the "cmpnt_col" argument in plot.deldir() has been 
##      changed from "num" to "labels".  There is a new 
##      function getNbrs(), and the function tileInfo() has 
##      been modified to include output from getNbrs(). 
##      Please consult the help.
library(dismo)
## Loading required package: raster
## Loading required package: sp
## 
## Attaching package: 'raster'
## The following object is masked from 'package:dplyr':
## 
##     select
  1. Create and view voronoi polygon
sp_voronoi <- municipalities_centroid %>%
  as("Spatial") %>%
  voronoi() %>%
  st_as_sf()

sp_voronoi %>% ggplot() + 
  geom_sf()

  1. Clip vornoi to SP state border (See CLIP EXAMPLE). In addition, ensure to check projections!
sp_voronoi_clip <- sp_voronoi %>% st_intersection(st_union(SP_border))
## Warning: attribute variables are assumed to be spatially constant throughout
## all geometries
sp_voronoi_clip %>% ggplot() + geom_sf()

Extra Activities 2 - Count points within a polygon

  1. Perform operations and view results #```{r} mun_house <- municipalities %>% st_join(Housing) %>% group_by(COD_MUN) %>% Count()

mun_house %>% ggplot() + geom_sf(aes(fill=n), col=NA) + scale_fill_gradient(low=“#ccece6”, high = “dark green”) + theme_classic() #```