polarsandwich
polarsandwich

Reputation: 135

Binding multiple shapefiles results in rownames error

I've got a list of around 20 shapefiles that I want to bind into one. These shapefiles have different number of fields - some have 1 and some have 2. Examples are shown below:

 # 1 field 
 > dput(head(shp[[1]]))
  structure(list(area = c(1.60254096388, 1.40740270051, 0.093933438653, 
  0.609245720277, 22.892748868, 0.0468096597394)), row.names = 0:5, class = "data.frame")

 # 2 fields 
> dput(head(shp[[3]]))
  structure(list(per = c(61, 70, 79, 90, 57, 66), area = c(2218.8, 
  876.414, 2046.94, 1180.21, 1779.12, 122.668)), row.names = c(0:5), class = "data.frame")

I used the following code to bind them and it worked just as I wanted:

merged<- raster::bind(shp, keepnames= FALSE, variables = area)
writeOGR(merged, './shp', layer= 'area', driver="ESRI Shapefile")

However, I now need to subset one of the shapefiles in the list. I do it in this way:

shp[[3]]@data <- shp[[3]]@data %>% subset(Area >= 50)
names(shp[[3]]@data)[names(shp[[3]]@data) == "Area"] <- "area"

When I run the bind command, however, this now gives me an error:

merged<- raster::bind(shp, keepnames= FALSE, variables = area)

Error in `.rowNamesDF<-`(x, value = value) : invalid 'row.names' length
Calls: <Anonymous> ... row.names<- -> row.names<-.data.frame -> .rowNamesDF<-
Execution halted

I'm not sure why that is. The shapefile hasn't changed, they are just subsetted. I tried deleting the rownames in the way shown below and it still throws the same error.

rownames(shp[[3]]@data) <- NULL

What could it be?

Upvotes: 0

Views: 88

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47146

I think the problem is that that you subset @data (the attributes) but you should subset the entire object. Something like this

x <- shp[[3]]  # for simplicity
x <- x[x$Area >= 50, ]
names(x)[names(x) == "Area"] <- "area"
shp[[3]] <- x

Upvotes: 1

Related Questions