如何使用R创建没有尾随零的shapefile

时间:2016-04-14 11:09:47

标签: r dataframe shapefile

我正在创建一个shapefile,但数据列都有尾随零,例如:1.000000000000000

如何将尾随零限制为2位,例如:1.00?

示例代码:

library(rgdal)
library(sp)

coords <- cbind(c(631145, 631757, 631928, 631664, 631579, 631281), c(6967640, 6967566, 6968027, 6967985, 6968141, 6968009))
poly <- Polygons(list(Polygon(coords)),"coords")
poly.sp <- SpatialPolygons(list(poly))

df<- data.frame(id = getSpPPolygonsIDSlots(poly.sp))
row.names(df) <- getSpPPolygonsIDSlots(poly.sp)

spdf <- SpatialPolygonsDataFrame(poly.sp, data=df)
spdf@data$VALUE <- 1
writeOGR(spdf, "shapes", "testShape", driver="ESRI Shapefile", overwrite=TRUE)

当我在文本编辑器(Notepad ++)中打开.dbf文件时,1显示为尾随零。

1 个答案:

答案 0 :(得分:1)

你的shapefile DBF将它存储为Real值,你想要整数。

> ogrInfo("./shapes","testShape")
Source: "./shapes", layer: "testShape"
Driver: ESRI Shapefile; number of rows: 1 
Feature type: wkbPolygon with 2 dimensions
Extent: (631145 6967566) - (631928 6968141)
LDID: 87 
Number of fields: 2 
   name type length typeName
1    id    4     80   String
2 VALUE    2     24     Real

R默认将其数字列创建为浮点数。列类是“数字”:

> class(spdf$VALUE)
[1] "numeric"

将其更改为“整数”L

> class(spdf$VALUE)="integer"
> class(spdf$VALUE)
[1] "integer"

并重写你的shapefile:

> writeOGR(spdf, "shapes", "testShape", driver="ESRI Shapefile", overwrite=TRUE)

现在

> ogrInfo("./shapes","testShape")
Source: "./shapes", layer: "testShape"
Driver: ESRI Shapefile; number of rows: 1 
Feature type: wkbPolygon with 2 dimensions
Extent: (631145 6967566) - (631928 6968141)
LDID: 87 
Number of fields: 2 
   name type length typeName
1    id    4     80   String
2 VALUE    0     10  Integer

shapefile DBF中的整数字段。完成工作。