1

I have a SpatialPolygonsDataFrame in R, from which I would like to extract a vector of one of the columns. This can be done easily by using the $ notation, e.g. dataFrame$columnName. My code however needs to pass the column names as strings, in which case I would normally use the bracket notation dataFrame[,'columnName'] to get the same result. R-spatial however, per the documentation, doesn't seem to allow this, returning instead a full SpatialPolygonsDataFrame object with geometry added to the single requested column.

How can I go from a string of the column name to just a vector of the data in that column? I'd prefer to do this without creating a separate non-spatial dataframe if possible.

1
  • Call the slot explicitly ie., x@data[,"colname"] Commented Jul 18, 2018 at 21:39

2 Answers 2

4

You can subset the @data slot which is a plain data frame, but its not always a good idea to access members of an object class via slots, in which case you can convert to a plain data frame with as.data.frame, which drops the geometry and gives back a plain data frame:

bar_vector = as.data.frame(spfoo)[,"bar"]

One advantage of using as.data.frame instead of the slot is that this will also work if your spatial object is one of the new sf classes.

1
  • Nice that this will work with sp and sf objects. Commented Jul 18, 2018 at 23:32
3

You could use the $-operator as a function

`$`(dataFrame, 'columnName')

Or you could make use of the function extract2() from the magrittr package, that is basically the same as $ or [[:

magrittr::extract2(dataFrame, 'columnName')

The motivation behind extract2() is actually that it can be used in pipes. So you could also do

library(magrittr)
dataFrame %>% extract2('columnName')

All these solutions also work with sf objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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