inlabru-org / inlabru

inlabru
https://inlabru-org.github.io/inlabru/
73 stars 21 forks source link

fm_spTransform error #156

Closed kkemink closed 1 year ago

kkemink commented 1 year ago

Hi, I am attempting to do a transformation of my coordinate system from meters to kilometers for length units but keep getting tripped up in errors. I haven't been able to find a solution and was hoping someone on here might have encountered (and solved) a similar problem. Code and error below. Any suggestions much appreciated. I should note I've tried doing this in an Albers projection as well although I was pretty sure from the beginning it was user-error and not the projection that was an issue.

I used INLA version 20.09.25 and inlabru 2.5.3

projt<-st_read(toyshape.shp) train<-read.csv(toy.csv) st_crs(projt)<-4326 crs.m<-crs(projt) crs.KM<-fm_crs_set_lengthunit(crs.m,unit="kilometre") Loc2<-st_as_sf(train,coords=c("LONG1","LAT1"),crs = 4326) Loc<-fm_spTransform(Loc2,crs.m,crs.KM) toy.csv toyshape.csv

finnlindgren commented 1 year ago

The code above can't be tested since toyshape.csv isnt toyshape.shp. But the original problem was twofold:

  1. the fm_functions don't support sf objects yet, and
  2. the epsg:4326 crs needed special support, that is implemented in 2.5.3.9002.

For now, you need to convert your objects to sp before calling inlabru and fm_* functions. There is a feature/sf branch in development but it's not ready for general testing yet.

To construct the "km" version of epsg:4326, use this:

crs.m <- as(st_crs("epsg:4326"), "CRS")
crs.km <- fm_crs_set_lengthunit(crs.m, unit = "kilometre")

You can covert that back to st_crs and use general sf transformations, or convert your data object to sp and use fmspTransform (or just spTransform; the fm* version handles additional types of objects).

finnlindgren commented 1 year ago

Also note that the unit change has no actual effect on the 4326 specification, since the coordinates are in longlat. Even though it does have the ellipsoid radius specified in metres, that is always the case, and is not affected by changing the length unit of the projection itself.

finnlindgren commented 1 year ago

The fm_spTransform methods are now being phased out, and the replacement fm_transform and fm_crs methods support sf objects. For length units, there's fm_length_unit(crs) <- "km" that works for both sf crs and sp CRS objects.

If you're still having issues, please upgrade to the most recent development version of inlabru (soon on CRAN as 2.7.0) and the latest INLA testing version, and try again.