Removing columns in a SpatialPolygonsDataFrame in R?
Use the syntax object_ name[,-(1:5)]
to remove columns 1 to 5 or object_name[,-c(1,5)]
to drop columns 1 and 5. See the example below (with comments):
require(maptools)
#load shapefile from maptools package to make a reproducible example.
xx <- readShapeSpatial(system.file("shapes/sids.shp", package="maptools")[1],
IDvar="FIPSNO", proj4string=CRS("+proj=longlat +ellps=clrk66"))
class(xx) #check the object class
#[1] "SpatialPolygonsDataFrame"
#attr(,"package")
#[1] "sp"
head(xx@data,3) #print first three rows from the slot 'data'
AREA PERIMETER CNTY_ CNTY_ID NAME FIPS FIPSNO CRESS_ID BIR74 SID74
0.111 1.392 1904 1904 Alamance 37001 37001 1 4672 13
0.066 1.070 1950 1950 Alexander 37003 37003 2 1333 0
0.061 1.231 1827 1827 Alleghany 37005 37005 3 487 0
NWBIR74 BIR79 SID79 NWBIR79
1243 5767 11 1397
128 1683 2 150
10 542 3 12
xxx <- xx[,-(1:5)] #remove columns 1 to 5
head(xxx@data,3) #print the subsetted data frame
FIPS FIPSNO CRESS_ID BIR74 SID74 NWBIR74 BIR79 SID79 NWBIR79
37001 37001 1 4672 13 1243 5767 11 1397
37003 37003 2 1333 0 128 1683 2 150
37005 37005 3 487 0 10 542 3 12
To use the names of columns, you can implement Joris Meys' solution here, which consists in creating a list of names and using it to drop the columns.
For example:
drops <- c("AREA","PERIMETER") # list of col names
xxx <- xx[,!(names(xx) %in% drops)] #remove columns "AREA" and "PERIMETER"
Here is one alternative using the select function from package dplyr
:
library(dplyr)
SPDF@data <- SPDF@data %>%
select(1, 3) #keeps column 1 and column 3 in the spdf object.