I am trying to subset SpatVector from terra in parallel with the help of foreach .
My ultimate aim is to extract pixels of rasters from several tiles using specific polygons. The extraction of pixels works, but not the subseting of specific polygons.
Take the bellow code as a reproducible example for this problem. No message need to show up if that works.
# Libraries
library(terra)
library(foreach)
library(doParallel)
# Example vector
vector <- vect(system.file("ex/lux.shp", package="terra"))
aoi <- vector$NAME_2
# Set up cluster
threads <- 4
cl <- makeCluster(threads)
registerDoParallel(cl)
# Parallel loop
extraction <- foreach(i = 1:length(aoi),
.packages = c("terra"),
.inorder = F) %dopar% {
IDoi <- aoi[i]
tile_vector <- subset(vector,
NAME_2 == IDoi,
NAME_2,
NSE = TRUE)
}
# Stop cluster
stopCluster(cl)
gc()
The resulting error message says Error in { : task 1 failed - "error in evaluating the argument 'x' in selecting a method for function 'as.list': NULL value passed as symbol address"
Any idea?
Before I parallelized this, I'd get my loop working in a simple
forloop, as that is where the error propagates. I'm assuming you want 12 polygons returned rather than overwriting and simply returning the last:Wrapping things deeper can obscure error messages, though in the above, it was pointing to subset, even as wrapped in foreach & %dopar%.
terra::subsetsuggests NSE=FALSE for wrapped evaluation. And perhaps the wrapping within{explains why, in my case, 'NAME_2' wasn't being found, even after establishing 'terra::subset('. And it is just as likely I've misinterpreted your needs, but I'd move on to parallel once these issues were addressed.