如何加速大分辨率栅格间重叠对应单元格的提取操作
Efficient Solution for Overlapping Raster Cell Extraction
Your current approach is slow because it loops through every low-resolution cell individually, creating and projecting polygons one at a time. Instead, use vectorized operations in terra to process all low-resolution cells in bulk:
Step-by-Step Optimized Code
library(terra) # Create example rasters (same as your original) highRes <- rast() res(highRes) <- c(0.1, 0.1) highRes[] <- sample(1:10, ncell(highRes), replace = TRUE) lowRes <- rast(res = c(1, 1), xmin = -170, xmax = -50, ymin = 0, ymax = 80) lowRes[] <- 1 lowRes <- shift(lowRes, dx = 0.02, dy = 0.03) # Not aligned # 1. Ensure both rasters share the same CRS (project lowRes if needed) lowRes_proj <- project(lowRes, crs(highRes)) # 2. Convert entire low-res raster to individual cell polygons (no dissolution) low_polys <- as.polygons(lowRes_proj, dissolve = FALSE) # Add a unique ID for each low-res cell to track results low_polys$cell_id <- seq_len(nrow(low_polys)) # 3. Extract high-res values with exact coverage weights in one bulk operation result <- extract(highRes, low_polys, weights = TRUE, exact = TRUE) # Result structure: # - ID: Matches cell_id in low_polys (low-res cell identifier) # - value: Value from high-res cell # - weight: Fraction of the high-res cell covered by the low-res cell
Why This Is Faster
- No loops: Avoids the overhead of iterating through each low-res cell in R, which is slow for large datasets.
- Bulk processing:
terrahandles polygon intersections and value extraction in optimized C++ code, which is far more efficient than per-cell operations. - Minimized redundant operations: Converts all low-res cells to polygons in one step instead of creating a new raster/polygon for each cell.
Additional Optimizations
- Memory management: For extremely large global rasters, consider processing in chunks using
terra::spatSampleor splitting the low-res raster into regions if memory is constrained. - File formats: Store rasters in efficient formats like GTiff with LZW compression to reduce I/O time when reading from disk.
- CRS alignment: If your rasters already share the same CRS, skip the
projectstep to save time.
内容的提问来源于stack exchange,提问作者Pascal
相关产品推荐
相关产品推荐

