4

I am creating a WRT string from a specialPolygons object in R.

However I am surprised by the number of digits in the output. Is there a way to reduce it?

x = sp::SpatialPolygons(Srl = list(sp::Polygons(srl = list(sp::Polygon(coords = cbind(c(-19.8, -19.9, -19.9, -19.8, -19.8),c(148, 148, 148.2, 148.2, 148)))), ID = "1")), pO = 1:1)
rgeos::writeWKT(x)

This gives me:

"POLYGON ((-19.8000000000000007 148.0000000000000000, -19.8999999999999986 148.0000000000000000, -19.8999999999999986 148.1999999999999886, -19.8000000000000007 148.1999999999999886, -19.8000000000000007 148.0000000000000000))"
RockScience
  • 17,932
  • 26
  • 89
  • 125
  • Based on a chat I had with [@Spacedman](http://chat.stackoverflow.com/transcript/message/34211117#34211117), this would appear to demand a C level tinkering. – Roman Luštrik Nov 23 '16 at 09:55
  • Specifically, this line here https://gitlab.com/geos/libgeos/blob/svn-trunk/src/geom/Coordinate.cpp#L43 seems to set the precision to "17". Pretty well hard coded in there. – Spacedman Nov 23 '16 at 13:19
  • Someone post as answer? I guess a hacky alternative is to post-process `writeWKT` with a regular expression to discard unwanted significant digits ... – Ben Bolker Nov 23 '16 at 14:51

2 Answers2

2

Functions in the excellent new sf package seem to work more like you'd hope:

library(sf)
st_as_text(st_as_sfc(x))
## [1] "POLYGON((-19.8 148, -19.9 148, -19.9 148.2, -19.8 148.2, -19.8 148))"
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
1

this works, annoying to need 3 pkgs instead of 1, but :)

library(geojson)
library(wellknown)
library(jsonlite)
geoj <- as.geojson(x)
geojson2wkt(fromJSON(geoj, FALSE)$features[[1]]$geometry, fmt = 1)

#> [1] "POLYGON ((-19.8 148.0, -19.9 148.0, -19.9 148.2, -19.8 148.2, -19.8 148.0))"
sckott
  • 5,755
  • 2
  • 26
  • 42
  • Is there any way to use writeWKT() directly? Instead of import other dependency like sf package or geojson. – Ranger Way Jun 18 '18 at 07:59
  • @RangerWay i don't know, but i'm curious why. do you have trouble installing `geojson`, i know many people having trouble installing `sf` – sckott Jun 18 '18 at 13:54