四舍五入 R 简单特征线串几何坐标

Rounding R simple features linestring geometry coordinates

我需要将一个简单要素对象(包含大约 1,000,000 个线串要素)的坐标四舍五入到最接近的小数点后 5 位。下面的代码正确地做到了这一点,但运行时非常慢,因为 for 循环的最后一行 (indata$geometry[i] <- st_linestring(coords) 每次迭代需要几秒钟。

有谁知道更有效的编码方式吗?

indata <- st_read(dsn=dir, layer=layer)
indata <- st_cast(indata,"LINESTRING")

for (i in 1:nrow(indata)) {
  coords <- st_coordinates(indata$geometry[i])
  coords <- round(coords, 5)
  indata$geometry[i] <- st_linestring(coords) #This is the slow part
}

我认为如果不写出 shapefile,您就无法改进现有的东西。限制似乎是处理线串。但是,您可以使用 st_set_precision 函数设置精度并写出文件。在您写入文件之前,它不会改变几何精度。您可以在 sf 手册的 page 48 上的 sf 手册的 st_binary 部分中阅读有关精度如何工作的更多信息。基本上跟零的个数有关。

outdata <- st_set_precision(indata, precision=10^5)
st_write(outdata, "/path/to/file.shp")
indata <- st_read("/path/to/file.shp")