Tuesday 19 January 2016

How to add a field to a shapefile using R



This question is trying to make sense of a post that already exists that looks good, but is failing in practice.


The second ranked answer uses the foreign package to read a shapefile attribute table as a .dbf, then allows @mdsummer to add a field to the table as an additional attribute.


I am using Raster and Shapefiles packages (shapefiles borrows the foreign read and write dbf).


library(raster); library(shapefiles)
shp<-shapefile(ZoneShape);

shp

>class : SpatialPolygonsDataFrame

nfeatures : 213
extent : 577829.3, 582592.8, 3837297, 3839300 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=15 +datum=NAD83 +units=m +no_defs +ellps=GRS80 +towgs84=0,0,0
nvariables : 1
names : OBJECTID
min values : 24571
max values : 28496

Now I'll read my attribute table:


shp.AT<-read.dbf(gsub(".shp", ".dbf", ZoneShape))


class(shp.AT)
>[1] "list"

shp.AT is a list that contains an index produced by R and the Shapefile's OBJECTID. Their are 213 records, but the length of the list is 2.


I'm not a great programmer, but I know I can't add a field to a list.


shp.AT$GID<-1:nrow(ZoneShape)
>[3] ERROR: nrow(ZoneShape)

nrow(ZoneShape)

>nrow(shp.AT)

# "nothing is returned!"


@mdsummer includes an "as.is = TRUE" in the read.dbf statement. Not sure what that might have done in the past, but R returns an error when this is included.


If I modify my new field slightly:


shp.AT$GID<- 1:length(ZoneShape)
shp.AT

This time, no error. My list of ID's is again reported along with my new GID field, but:


>$GID

[1] 1

If this worked as expected, I would overwrite the old DBF with the write.dbf command.


So, a couple questions really: Has the source changed, or is @mdsummer's post incorrect? or, am I totally missing something?


and (most importantly) how can I add fields to my shapefile attributes.


I also have a cross-posting on Overflow



Answer



The solution is less complicated than I was making it.


shp<-shapefile(ZoneShape)


shp$GID<-1:nrow(ZoneShape)

write.shapefile(shp, gsub(ZoneShape, ".shp", ""))

Thanks to vitale232


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...