Wednesday, March 04, 2020

How to remove columns in SpatialPolygonsDataFrame in R?

If you have a spatial polygon data frame (SPDF) and you would want to remove some columns, how do you do it?  You can use R to remove columns in SpatialPolygonsDataFrame .

Use the syntax object_ name[,-(1:10)] to remove columns 1 to 10 or object_name[,-c(1,10)] to drop columns 1 and 10.


#load shapefile from maptools package
w <- readShapeSpatial(system.file("shapes/sample.shp", package="maptools")[1],
                   IDvar="FIPSNO", proj4string=CRS("+proj=longlat +ellps=clrk66"))

class(xx) #check the object class
#[1] "SpatialPolygonsDataFrame"
#[1] "sp"
#remove columns 1 to 10 
ss <- w[,-(1:10)]
#or use column names to remove them 
rem <- c("name1","name2") # list of column names
final <- rem[,!(names(rem) %in% drops)] #remove columns "name1" and "name2"


Post a Comment