-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathadd_country_to_checklist.R
45 lines (36 loc) · 1.36 KB
/
add_country_to_checklist.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# This script assigns countries to a list of plants based on their geographical coordinates.
# It utilizes the 'terra' package for spatial operations and requires CSV files
# with plant information (these files can be generated by `create_plant_cheklist_by_beee.R`)
# and a world boundary shapefile in WGS 84 (EPSG:4326) projection.
library(terra)
library(tidyverse)
config <- config::get()
DATA_FOLDER <- config$data_folder
# Find checklist data files
listado_archivos <- fs::dir_ls(path = DATA_FOLDER, glob="*_list.csv")
crs_wgs84 <- "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"
# Download country borders from https://www.naturalearthdata.com/downloads/50m-cultural-vectors/
world_info <- vect(config$country_borders_path)
attr_country <- c("ISO_A2", "NAME_ES")
for(f in listado_archivos) {
cat("Procesando archivo", fs::path_file(f), "\n")
data <- read_csv(f)
if (nrow(data) == 0) {
next
}
data_names <- names(data)
data_names <- c(data_names, attr_country)
data <- vect(
as.matrix(select(data, longitude, latitude)),
crs=crs_wgs84,
atts=as.data.frame(select(data, -longitude, -latitude))
)
country_data <- terra::extract(
world_info, data
)
data <- cbind(data, country_data)
data <- as.data.frame(data, geom = "XY") %>%
rename("longitude"=x, "latitude"=y) %>%
select(any_of(data_names))
write_csv(data, f)
}