Reputation: 1
I'm trying to append two SpatialPolygonDataFrames that have different fields. I've been using spRbind and have created unique row ids for each data frame using spChFIDs. But I still get the following error.
Error in rbind(deparse.level, ...) : numbers of columns of arguments do not match
An example is block-level shapefile date from NHGIS for the states of Missouri and Illinois. Missouri has 17 fields and Illinois has 18.
Missouri: OGR data source with driver: ESRI Shapefile Source: "../nhgis0030_shapefile_tl2010_290_block_2010", layer: "MO_block_2010" with 343565 features It has 17 fields
Illinois: OGR data source with driver: ESRI Shapefile Source: "../nhgis0030_shapefile_tl2010_170_block_2010", layer: "IL_block_2010" with 451426 features It has 18 fields Integer64 fields read as strings: ALAND10 AWATER10
Upvotes: 0
Views: 423
Reputation: 47191
You can use the bind
method from the raster
package for this
As always, first set up some example data (you should have include some in your question):
library(raster)
# example data
p <- shapefile(system.file("external/lux.shp", package="raster"))
p
#class : SpatialPolygonsDataFrame
#features : 12
#extent : 5.74414, 6.528252, 49.44781, 50.18162 (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
#variables : 5
#names : ID_1, NAME_1, ID_2, NAME_2, AREA
#min values : 1, Diekirch, 1, Capellen, 76
#max values : 3, Luxembourg, 9, Wiltz, 312
p1 <- p[p$NAME_2=='Mersch', ]
p2 <- p[p$NAME_2=='Diekirch', ]
p3 <- p[p$NAME_2=='Remich', ]
# remove all fields for p1
p1 <- as(p1, 'SpatialPolygons')
# remove one field for p3
p3$NAME_1 <- NULL
# add a new field
p3$newfield <- 25
Now we have the example data, use bind
to combine the three SpatialPolygon* objects:
x <- bind(p1, p2, p3)
data.frame(x)
# ID_1 NAME_1 ID_2 NAME_2 AREA newfield
#1 NA <NA> <NA> <NA> NA NA
#2 1 Diekirch 2 Diekirch 218 NA
#3 2 <NA> 7 Remich 129 25
Upvotes: 2