I have a dataframe with the occurrence of different species. I want to create a raster for different species in the species column but then I want to stack the raster_list into a raster stack but I get error message that rasters have different extent
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
The process can be simplified. And to create raster(s) with species occurence, you should rasterize the coordinates.
Now, let's create spatial vector of the species and simple raster with extent covering all species. Note: you can manage the resolution by changing
nrows(number of rows) andncols(number of columns in raster). Or, you can provideresolutionparameter toterra::rast()function. Extent in longitude divided by number of columns gives the resolution on longitudinal axis, and the same for latitude: "vertical"extent / nrows = resolution. Instead of number of rows/cols you can provideresolutionparameter =>nrowsandncolswill be created appropriately. For details please check help to?terra::rast()And let's rasterize the points:
Created on 2024-02-15 with reprex v2.1.0