jhhwilliams
jhhwilliams

Reputation: 2582

How to create shapefile without trailing zeros using R

I am creating a shapefile but the data columns all have trailing zeros eg: 1.000000000000000

How do I limit the trailing zeros to 2 digits eg: 1.00 ?

Sample code:

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)

When I open the .dbf file in a text editor (Notepad++) the 1 is displayed with trailing zeros.

Upvotes: 1

Views: 407

Answers (1)

Spacedman
Spacedman

Reputation: 94277

Your shapefile DBF is storing it as a Real value, and you want Integers.

> 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 creates its numeric columns by default as floating point numbers. The column class is "numeric":

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

Change this to "integer"L

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

And rewrite your shapefile:

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

And now

> 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

Integer field in the shapefile DBF. Job done.

Upvotes: 1

Related Questions