EcologyR / mappestRisk

Other
0 stars 0 forks source link

Project data with `map_risk()` to user-specified `sf` with CRS different to WGS84 #51

Closed dario-ssm closed 1 month ago

dario-ssm commented 1 month ago

Hi! Trying to use map_risk() to extract WorldClim data to a spatial feature (sf) object, I found that the function only works if my sf object is the same as the geodata default (WGS 84 or EPSG 4326). I think users might often want to extract data into their local/regional polygons with other CRSs.

For example, in this following case:

tunisia <- geodata::world(path = tempdir()) |> 
  sf::st_as_sf() |> 
  sf::st_transform(3035) |> 
  dplyr::filter(GID_0 == "TUN")

set.seed(2024)

therm_bounds <- data.frame(tval_left = rnorm(100, 25, 1),
                           tval_right = rnorm(100, 33, 1))
rast_example <- map_risk(t_vals = therm_bounds,
                         path = tempdir(),
                         region = tunisia) ### error 

An error occurs when CRS system is 3035 (ETRS89-extended / LAEA Europe). Should we consider allowing alternative CRS inputs for the argument "region"? and/or adding another argument for the crs of the output raster?

AMBarbosa commented 1 month ago

The error message says "unable to find an inherited method for function ‘project’ for signature ‘"sf"’. It's not because the map is in a different CRS, but rather because it is of class 'sf', whereas the map_risk help file specifies that region should be "a terra::SpatVector polygon map (obtained with terra::vect()". You won't get the error if I instead run:

rast_example <- map_risk(t_vals = therm_bounds,
                         path = tempdir(),
                         region = terra::vect(tunisia))

...or if you make tunisia originally as a SpatVector rather than an sf map:

library(tidyterra)  # if you want to use tidyverse functions on 'terra' maps

tunisia <- geodata::world(path = tempdir()) |> 
  terra::project("EPSG:3035") |>
  dplyr::filter(GID_0 == "TUN")

rast_example <- map_risk(t_vals = therm_bounds,
                         path = tempdir(),
                         region = tunisia)

Anyway, I've now implemented the possibility of using also 'sf' input maps in map_risk. So, if you pull the latest changes, your original code should now work.