【发布时间】:2023-01-17 08:37:04
【问题描述】:
在我下面的玩具/示例代码中,我制作了一个覆盖世界的网格,然后使用此网格将一个大型复杂的全球数据集拆分为每个网格单元格的一个文件。在我的实际工作中,这是一个瓶颈,需要很长时间。我会很感激一些关于优化它的想法和想法。我通过利用并行处理取得了一些成功,但我也认为它可以做得“更聪明”。
library("sf")
library("terra")
library("glue")
library("rnaturalearth")
library("tidyverse")
dir.create("tmp")
ogr2ogr_path <- "C://Program Files//QGIS 3.26.1//bin//ogr2ogr.exe"
## Make some grid cells
world_grid <- rast(nrows=1, ncols=1, xmin=-180, xmax=180, ymin=-90, ymax=90, crs="epsg:4326") %>%
st_bbox() %>%
st_as_sfc() %>%
st_make_grid(cellsize = 10) %>%
st_as_sf()
make_grid_cells <- function(grid_id, world_grid) {
output_name <- glue("tmp/polygon_{grid_id}.gpkg")
st_write(world_grid[grid_id,],
output_name,
append = FALSE,
quiet = TRUE)
return(output_name)
}
grid_cell <- lapply(1:nrow(world_grid), make_grid_cells, world_grid = world_grid)
## Get some sample data
ne_countries(type = "countries", scale = "large", returnclass = "sf") %>%
select(iso_a2) %>%
st_write("tmp/world_polygons.gpkg")
## Split the worldwide data into tiles
split_world_to_tiles <- function(tile_template_area, worldwide_data) {
output_name <- gsub("polygon", "worldwide_poly", tile_template_area)
grid_poly <- st_read(tile_template_area, quiet=T)
box <- grid_poly %>% st_bbox()
command <- glue('{double_quote("C://Program Files//QGIS 3.26.1//bin//ogr2ogr.exe")} -spat {box$xmin} {box$ymin} {box$xmax} {box$ymax} -clipsrc spat_extent -f GPKG {output_name} {worldwide_data} -nlt GEOMETRYCOLLECTION')
system(command)
}
split_worldwide_data <- lapply(grid_cell, split_world_to_tiles, worldwide_data = "tmp/world_polygons.gpkg")
【问题讨论】: