在R中遍历栅格增量值批量创建新栅格数据集
Hey there! You're already halfway there with your code—let's get that loop working so you can generate all 9 raster outputs automatically. The key is to iterate over your increment sequence, apply the threshold logic to each, and save the results with meaningful filenames.
First, a quick note: avoid using list as a variable name since it's a built-in R function (it can cause unexpected behavior later). Let's rename that to something like increments instead.
Here's the full, working code with explanations:
# Load required library library(raster) # Set working directory to your folder path setwd("C:/Path/To/Folder") # Load your source raster (values between 100-500) r <- raster("Source_Raster.tif") # Create your sequence of increments (100, 150, ..., 500) increments <- seq(100, 500, 50) # Loop through each increment to generate and save the thresholded raster for (i in increments) { # Apply threshold: set values > i to NA, keep values <= i thresholded_raster <- calc(r, fun = function(x) { x[x > i] <- NA return(x) }) # Create a descriptive filename (e.g., "raster_100.tif", "raster_150.tif") output_filename <- paste0("raster_", i, ".tif") # Save the raster to your working directory writeRaster(thresholded_raster, filename = output_filename, format = "GTiff", overwrite = TRUE) # Optional: Print progress update cat("Generated and saved:", output_filename, "\n") }
Breakdown of the key parts:
- Loop through increments: The
for (i in increments)loop goes through each value in your sequence one by one, no need to hardcode each threshold manually. - Dynamic threshold logic: Inside
calc(), we use the current incrementias the threshold instead of fixed numbers—this makes the logic reusable for every value in your sequence. - Unique filenames:
paste0()creates a distinct filename for each output raster, so you can easily tell which threshold each file corresponds to at a glance. - Save and overwrite:
writeRaster()exports the thresholded raster to your working directory. Settingoverwrite = TRUElets you re-run the code without errors if the files already exist.
Once you run this code, you'll have 9 new TIFF files in your folder, each containing only the values from your source raster that are less than or equal to the corresponding increment.
内容的提问来源于stack exchange,提问作者Lee Walston

