如何将含NDVI值的投影栅格转为保留网格结构的CSV/Excel
If you need to export your NDVI raster into a grid-style CSV where the first row contains metric longitude (x) values, first column contains metric latitude (y) values, and cells hold the corresponding NDVI values, here's a straightforward approach using R's tidyverse tools:
Step 1: Load Required Libraries
We'll use the raster package for handling raster data and tidyr (part of the tidyverse) to reshape the data from long to wide format.
library(raster) library(tidyr)
Step 2: Prepare Your Raster (or Load Existing)
Using your example raster for demonstration:
# Create sample raster (replace with your actual raster) r <- raster(ncol=10, nrow=10) values(r) <- 1:ncell(r) # Convert to long-format data frame with coordinates df <- as.data.frame(r, xy = TRUE)
Step 3: Reshape to Wide (Grid) Format
We'll use pivot_wider to turn x-values into columns and keep y-values as rows. We also reorder the rows so the highest latitude (top of the raster) appears first in the CSV:
# Pivot to grid format grid_df <- df %>% pivot_wider(names_from = x, values_from = layer) %>% arrange(desc(y)) # Reverse y order to match raster's top-to-bottom layout
Step 4: Export to CSV
Finally, write the grid data frame to a CSV file. Setting row.names = FALSE ensures we don't add extra row numbers:
write.csv(grid_df, "ndvi_grid.csv", row.names = FALSE)
What the Output Looks Like
For your sample raster, the resulting CSV will have:
- First column: y-values (from 81 down to -81)
- Column headers: x-values (-162, -126, ..., 162)
- Cells: Corresponding raster values (1-10 in the first row, 11-20 in the second, etc.)
Alternative with reshape2
If you prefer using reshape2 instead of tidyr, you can use dcast:
library(reshape2) grid_df <- dcast(df, y ~ x, value.var = "layer") grid_df <- grid_df[order(-grid_df$y), ] # Reorder rows to match raster layout write.csv(grid_df, "ndvi_grid.csv", row.names = FALSE)
This approach maintains the spatial grid structure of your raster, making it easy to map back to the original geographic coordinates in spreadsheet tools.
内容的提问来源于stack exchange,提问作者il nibbio

