[R-sig-Geo] subset SpatialPolygonsDataFrame using negative index?

Roger Bivand Roger.Bivand at nhh.no
Thu Oct 22 10:38:39 CEST 2009


On Wed, 21 Oct 2009, stubben wrote:

> 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

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

>
> # 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
>
>
>> 
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at stat.math.ethz.ch
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

-- 
Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of
Economics and Business Administration, Helleveien 30, N-5045 Bergen,
Norway. voice: +47 55 95 93 55; fax +47 55 95 95 43
e-mail: Roger.Bivand at nhh.no



More information about the R-sig-Geo mailing list