8

My spatial polygon data frame (SPDF) contains too many columns (variables) and I want to remove most of the columns entirely.

I know how to do this with a regular data frame in R, but I am unsure how to do this when dealing with object of class SpatialPolygonsDataFrame?

12

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"
1

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.
  • 2
    It makes me nervious operating on the @data slot using packages or functions not specifically designed for spatial objects. This is why there is a special version of merge, The base version of merge screws up the row names and breaks the relationships between the attributes and features. – Jeffrey Evans Nov 9 '17 at 23:32
0

The following command also does the trick, but you must know your column numbers:

temp<-df[c(1:6,99:103)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.