如何使用purrr::map重组列表中RasterStack/RasterBrick的图层
Got it, let's walk through how to group your RasterBrick layers by their bio names using purrr. I'll use sample data to make this concrete, so you can follow along and adapt it to your own dataset.
Step 1: Setup Sample Data (Skip if you have your own)
First, let's create a list of RasterBricks to work with. Each brick has layers named bio_1, bio_2, and bio_3:
library(raster) library(purrr) # Generate 3 sample RasterBricks set.seed(123) create_sample_brick <- function() { brick(nl = 3, nrow = 5, ncol = 5) %>% setNames(paste0("bio_", 1:3)) } brick_list <- list(create_sample_brick(), create_sample_brick(), create_sample_brick())
Step 2: Extract Unique Bio Layer Names
First, we need to get all the unique bio layer names we want to group by. This works even if your bricks have different sets of bio layers (though I assume they're consistent):
# Get sorted unique bio names across all bricks unique_bio_names <- brick_list %>% map(names) %>% # Get layer names from each brick flatten_chr() %>% # Combine into a single character vector unique() %>% # Keep only unique names sort() # Optional: ensure order is bio_1, bio_2, etc.
Step 3: Group Layers by Bio Name Using purrr
Now, we'll use purrr::map to iterate over each unique bio name, extract that layer from every brick in your list, and stack them into a new RasterBrick:
# Group layers into new RasterBricks grouped_bricks <- unique_bio_names %>% map(function(bio_name) { brick_list %>% map(~ .x[[bio_name]]) %>% # Extract the bio_name layer from each brick brick() # Combine extracted layers into a new RasterBrick }) # Name the list elements for clarity (optional but helpful) names(grouped_bricks) <- unique_bio_names
What this does:
- For each bio name (like
bio_1), we loop through your original list of bricks and pull out thebio_1layer from each one. - We then combine those individual layers into a single RasterBrick (use
stack()instead ofbrick()if you prefer a RasterStack).
Step 4: Convert to Numeric Matrix (As You Mentioned)
Once you have your grouped bricks, converting them to matrices is straightforward. You can use raster::values() or as.matrix():
# Convert each grouped brick to a matrix bio_matrices <- grouped_bricks %>% map(values) # Or map(as.matrix) depending on your needs
Notes
- If some bricks are missing a specific bio layer, this will throw an error. If that's a possibility, you can add a check with
purrr::possiblyto skip missing layers or handle them gracefully. - This approach keeps your code consistent with tidyverse/purrr style, avoiding explicit for loops and making it easy to extend if you add more bricks or bio layers later.
内容的提问来源于stack exchange,提问作者Javier Fajardo

