我有一些大型的shapefile,其中包含需要分解的数百万个多边形。根据shapefile的不同,我需要按组分解,或者只对所有文件使用st_union
。我一直在使用st_par
function,它对于大多数SF应用程序都非常有效。虽然当我在st_union
上使用此函数时,它返回一个列表,但我无法弄清楚如何使sf解散函数st_union
并行化。
任何建议将是最有帮助的!这是一个小代码段,用以说明我的观点。
library(sf)
library(assertthat)
library(parallel)
us_shp <- "data/cb_2016_us_state_20m/cb_2016_us_state_20m.shp"
if (!file.exists(us_shp)) {
loc <- "https://www2.census.gov/geo/tiger/GENZ2016/shp/cb_2016_us_state_20m.zip"
dest <- paste0("data/cb_2016_us_state_20m", ".zip")
download.file(loc, dest)
unzip(dest, exdir = "data/cb_2016_us_state_20m")
unlink(dest)
assert_that(file.exists(us_shp))
}
usa <- st_read("data/cb_2016_us_state_20m/cb_2016_us_state_20m.shp", quiet= TRUE) %>%
filter(!(STUSPS %in% c("AK", "HI", "PR")))
test <- usa %>%
st_par(., st_union, n_cores = 2)
最佳答案
我认为您可以通过对原始 st_par
function进行小的修改来解决您的特定问题。
但是,这只是一个快速而大胆的修复,可能会破坏该函数其他用途的代码。
函数的作者当然可以提供更好的解决方案...
library(parallel)
# Paralise any simple features analysis.
st_par <- function(sf_df, sf_func, n_cores, ...){
# Create a vector to split the data set up by.
split_vector <- rep(1:n_cores, each = nrow(sf_df) / n_cores, length.out = nrow(sf_df))
# Perform GIS analysis
split_results <- split(sf_df, split_vector) %>%
mclapply(function(x) sf_func(x), mc.cores = n_cores)
# Combine results back together. Method of combining depends on the output from the function.
if ( length(class(split_results[[1]]))>1 | class(split_results[[1]])[1] == 'list' ){
result <- do.call("c", split_results)
names(result) <- NULL
} else {
result <- do.call("rbind", split_results)
}
# Return result
return(result)
}