Skip to content

subset SpatialPolygonsDataFrame using negative index?

2 messages · Chris Stubben, Roger Bivand

#
I loaded a county map of New Mexico from  census.gov

nm <- readShapePoly("co35_d00.shp", proj4string=CRS("+proj=longlat"))

This map has 34 counties because Sandoval county occurs twice (which  
is funny since there is one missing in the maps database).   I'd like  
to remove the extra polygon which is very small, but a negative index  
doesn't work

# remove 13th row
n<-which(nm2 at data$AREA<0.0005)
n
[1] 13

# using negative index
nm1<-nm[-n,]
# only one county displayed on map
plot(nm1)
## because  plotOrder =1?
str(nm1,2)
Formal class 'SpatialPolygonsDataFrame' [package "sp"] with 5 slots
   ..@ data       :'data.frame':	33 obs. of  9 variables:
   ..@ polygons   :List of 33
   ..@ plotOrder  : int 1
   ..@ bbox       : num [1:2, 1:2] -109.1 31.3 -103 37
   .. ..- attr(*, "dimnames")=List of 2
   ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slots



##  this works, but I'm just wondering why the negative index doesn't  
work?  Am I doing something wrong?

nm2<-nm[c(1:12,14:34),]
plot(nm2)
str(nm2,2)
Formal class 'SpatialPolygonsDataFrame' [package "sp"] with 5 slots
   ..@ data       :'data.frame':	33 obs. of  9 variables:
   ..@ polygons   :List of 33
   ..@ plotOrder  : int [1:33] 22 23 28 2 25 3 9 12 24 14 ...
   ..@ bbox       : num [1:2, 1:2] -109.1 31.3 -103 37
   .. ..- attr(*, "dimnames")=List of 2
   ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slots



Thanks,

Chris Stubben
#
On Wed, 21 Oct 2009, stubben wrote:

            
No, the negative index doesn't work, I'll try to commit a fix to sp. In 
fact, I'd rather do:

nm <- readShapePoly("co35_d00.shp", proj4string=CRS("+proj=longlat"))
nm1 <- unionSpatialPolygons(nm, nm$COUNTY)
df <- as(nm, "data.frame")[-13,]
row.names(df) <- df$COUNTY
nm2 <- SpatialPolygonsDataFrame(nm1, df)

which makes a multipolygon for Sandoval and drops the attributes for the 
second member polygon.

Hope this helps,

Roger