我有一个包含不同物种出现情况的数据框。我想在物种列中为不同物种创建一个栅格,但随后我想将 raster_list 堆叠到栅格堆栈中,但我收到错误消息,表明栅格具有不同的范围
library(terra)
Occurrence_data <- data.frame(
lon = c(11.002470, 10.733250, 11.135831, 6.003845, 5.073000, 8.859500, 10.740000),
lat = c(59.05563, 63.57087, 60.15113, 62.40066, 60.11600, 58.62880, 59.95000),
species = c("B.terrestris", "B.pascuorum", "B.hortorum", "B.pratorum", "B.terrestris", "B.pascuorum", "B.hortorum")
)
###### Get unique species from the 'species' column
species_list <- as.factor(unique(Occurrence_data$species))
create_species_dataframes <- function(DF) {
# Get unique species from the 'species' column
species_list <- unique(DF$species)
# Create an empty list to store data frames
species_dataframes <- list()
# Loop through each unique species
for (species in species_list) {
# Filter the DataFrame for the current species
species_df <- DF[DF$species == species, ]
# Store the filtered DataFrame in the list
species_dataframes[[species]] <- species_df
}
# Returning the list of data frames
return(species_dataframes)
}
#call function to create individual dataframes for each species
Models<-create_species_dataframes(Occurrence_data)
# Function to convert data frame to raster
convert_to_raster <- function(df) {
# Convert the data frame to a raster
raster_data <- rast(df, type = "xy", crs = "EPSG:4326")
return(raster_data)
}
# Convert each data frame in the Models list to a raster
raster_list <- lapply(Models, convert_to_raster)
# Then, we combine all these rasters into stack.
for(x in raster_list ){
stackrasters<-stack(stackrasters,raster(x))
}```
Error in compareRaster(x): different extent
流程可以简化。要创建包含物种出现的栅格,您应该对坐标进行栅格化。
Occurrence_data <- data.frame(
lon = c(11.002470, 10.733250, 11.135831, 6.003845, 5.073000, 8.859500, 10.740000),
lat = c(59.05563, 63.57087, 60.15113, 62.40066, 60.11600, 58.62880, 59.95000),
species = c("B.terrestris", "B.pascuorum", "B.hortorum", "B.pratorum", "B.terrestris", "B.pascuorum", "B.hortorum")
) |>
dplyr::arrange(species)
species_list <- unique(Occurrence_data$species)
现在,让我们创建物种的空间向量和覆盖所有物种的简单栅格:
v <- terra::vect(Occurrence_data)
r <- terra::rast(nrows = 12, ncols = 12, crs = "EPSG:4326", ext = terra::ext(v))
让我们对点进行栅格化:
x <- terra::rasterize(v, r, fun = "count", by = "species")
names(x) <- species_list
x
#> class : SpatRaster
#> dimensions : 12, 12, 4 (nrow, ncol, nlyr)
#> resolution : 0.5052359, 0.4118392 (x, y)
#> extent : 5.073, 11.13583, 58.6288, 63.57087 (xmin, xmax, ymin, ymax)
#> coord. ref. : lon/lat WGS 84 (EPSG:4326)
#> source(s) : memory
#> names : B.hortorum, B.pascuorum, B.pratorum, B.terrestris
#> min values : 2, 1, 1, 1
#> max values : 2, 1, 1, 1
terra::plot(x)
创建于 2024-02-15,使用 reprex v2.1.0