./data
folder.
sf::read_sf()
function to load the data. Sampling is
straightforward: Apply the sf::st_sample
to the loaded
shapefile, but make sure to apply the sf::st_as_sf()
function afterward to receive a full-fledged data table (with a geometry
column only).
library(dplyr)
cologne <- sf::read_sf("./data/cologne.shp")
cologne_50_points <-
cologne |>
sf::st_sample(50) |>
sf::st_as_sf()
immigrants_cologne.tif
and
inhabitants_cologne.tif
files in the ./data
folder.
library(terra)
immigrant_rates <-
terra::rast("./data/immigrants_cologne.tif") * 100 /
terra::rast("./data/inhabitants_cologne.tif")
immigrant_rates_at_point <- terra::extract(immigrant_rates, cologne_50_points)
immigrant_rates_at_point
## ID immigrants_cologne
## 1 1 NA
## 2 2 NA
## 3 3 NA
## 4 4 7.017544
## 5 5 NA
## 6 6 NA
## 7 7 NA
## 8 8 NA
## 9 9 NA
## 10 10 NA
## 11 11 NA
## 12 12 NA
## 13 13 NA
## 14 14 6.060606
## 15 15 NA
## 16 16 NA
## 17 17 NA
## 18 18 NA
## 19 19 NA
## 20 20 NA
## 21 21 NA
## 22 22 NA
## 23 23 NA
## 24 24 9.708738
## 25 25 NA
## 26 26 9.523810
## 27 27 NA
## 28 28 NA
## 29 29 NA
## 30 30 NA
## 31 31 15.116279
## 32 32 NA
## 33 33 18.343195
## 34 34 NA
## 35 35 NA
## 36 36 NA
## 37 37 NA
## 38 38 NA
## 39 39 NA
## 40 40 22.826087
## 41 41 30.769231
## 42 42 NA
## 43 43 NA
## 44 44 NA
## 45 45 NA
## 46 46 NA
## 47 47 25.000000
## 48 48 12.500000
## 49 49 NA
## 50 50 4.545455
# There are a lot of missing values.
sf::st_buffer()
function. In that case, you should also set
a descriptive statistics function, e.g., with the option
fun = mean
and its helpful companion option to consider
missing values na.rm = TRUE
.
immigrant_rates_1000m_buffer <-
terra::extract(
immigrant_rates,
sf::st_buffer(cologne_50_points, 1000),
fun = mean,
na.rm = TRUE
)
immigrant_rates_1000m_buffer
## ID immigrants_cologne
## 1 1 19.94206
## 2 2 10.86003
## 3 3 24.60711
## 4 4 14.76968
## 5 5 41.19776
## 6 6 9.57958
## 7 7 16.66667
## 8 8 10.47115
## 9 9 NaN
## 10 10 NaN
## 11 11 NaN
## 12 12 12.31503
## 13 13 NaN
## 14 14 11.32721
## 15 15 12.56422
## 16 16 23.35796
## 17 17 NaN
## 18 18 19.11399
## 19 19 20.21938
## 20 20 10.07462
## 21 21 15.46473
## 22 22 12.01796
## 23 23 12.00779
## 24 24 18.82225
## 25 25 29.17175
## 26 26 30.28828
## 27 27 13.63636
## 28 28 15.35337
## 29 29 15.88380
## 30 30 NaN
## 31 31 18.26736
## 32 32 NaN
## 33 33 17.13602
## 34 34 11.13494
## 35 35 22.32109
## 36 36 NaN
## 37 37 15.40239
## 38 38 19.64879
## 39 39 17.75252
## 40 40 19.56511
## 41 41 20.06646
## 42 42 12.32524
## 43 43 16.97988
## 44 44 26.13186
## 45 45 41.42228
## 46 46 14.66044
## 47 47 15.21124
## 48 48 12.14026
## 49 49 13.99355
## 50 50 15.31588