nngeo icon indicating copy to clipboard operation
nngeo copied to clipboard

nngeo is failing with some CRS due to lack of units

Open latot opened this issue 1 year ago • 6 comments

Hi, I found this to fail here, is also related to https://github.com/r-spatial/sf/issues/2299.

points <- sf::st_sfc(
  sf::st_point(c(0, 1)),
  sf::st_point(c(0, 2)),
  crs = 'LOCAL_CS["planar", UNIT["METER",1]]'
)

points2 <- sf::st_sfc(
  sf::st_point(c(0, 1)),
  sf::st_point(c(0, 2)),
  crs = 'LOCAL_CS["planar", UNIT["METER",1]]'
)

nngeo::st_nn(points, points2)
projected points
Error in if (!is.na(crs_units) & crs_units != "m") { : 
  argument is of length zero

Here the line: https://github.com/michaeldorman/nngeo/blob/fcfde8ee0d236494aad120e0b86b5b21d7a2c7b0/R/st_nn_pnt_proj.R#L61

For some reason, SF is not setting the units for this CRS, maybe is only setting the ones that have the shortcut of numeric value, like 4326 for WGS84.

Thx.

latot avatar Dec 19 '23 17:12 latot

Hi, after check this on SF package, this issue is generated because nngeo is trying to read from proj4string:

https://github.com/michaeldorman/nngeo/blob/fcfde8ee0d236494aad120e0b86b5b21d7a2c7b0/R/st_nn_pnt_proj.R#L58

We can access to the params using sf::st_crs()$something, the point is that proj4string is replaced with WKT2, and that causes to new CRSs can not be read.

The solution is use directly the units from SF package, as described: https://github.com/r-spatial/sf/issues/2299#issuecomment-1863385408

That should fix this all above this, searching on the project, can't found any more causes where this can affect, if you know some case would be good to be fixed too.

Thx!

latot avatar Dec 19 '23 20:12 latot

Thanks! The error is now solved in https://github.com/michaeldorman/nngeo/commit/91085c0851dc9dc1f7e2442bba847d23aa0149b1 (the case is treated as a unitless CRS)

michaeldorman avatar Dec 21 '23 11:12 michaeldorman

Hi! sadly that does not fix the issue, this comes of what sf::st_crs()$units access to a PRoj4String parameter, the point there is that not all WKT2 has a Proj4String expression, so some WKT2 will not have a value there.

But you can use sf::st_crs()$ud_unit https://github.com/r-spatial/sf/issues/2299#issuecomment-1863182678 which always retrieve the unit from the CRS.

latot avatar Dec 21 '23 17:12 latot

Think I got it, thanks. Will appreciate if you can please check again. The CRS unit is extracted using sf::st_crs()$ud_unit.

michaeldorman avatar Dec 22 '23 16:12 michaeldorman

Hi!, now seems to be working.

latot avatar Feb 01 '24 20:02 latot

Great, thanks for checking!

michaeldorman avatar Feb 14 '24 12:02 michaeldorman

@michaeldorman is possible to upgrade a new CRAN version pls?

latot avatar Apr 16 '24 21:04 latot

Done https://cran.r-project.org/web/packages/nngeo/index.html

michaeldorman avatar Apr 17 '24 09:04 michaeldorman