如何在R中使用write_sf限制DBF文件的小数位数?
解决write_sf导出Shapefile时DBF小数位数过多的问题
你用st_set_precision没用是因为这个函数管的是几何坐标的存储精度,和DBF属性表的小数位数没关系。要限制DBF里的小数位数,得先处理属性表中的数值列,再导出:
先处理属性表的数值字段,统一保留2位小数:
基础R实现代码:# 筛选出所有数值类型的属性列 num_cols <- sapply(temp_points@data, is.numeric) # 对每个数值列保留2位小数 temp_points@data[num_cols] <- lapply(temp_points@data[num_cols], round, digits = 2)用dplyr的话写法更简洁:
library(dplyr) temp_points@data <- temp_points@data %>% mutate(across(where(is.numeric), ~round(., 2)))处理完属性列后,再执行导出:
write_sf(temp_points, "temp_points.shp")
这样导出的DBF文件里,数值字段就只会保留2位小数,不会出现大量多余的零了。
内容的提问来源于stack exchange,提问作者EmburMaps
相关产品推荐
相关产品推荐

