R – Extracting Column from R Spatial DataFrame Without $ Notation

r

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.

Best Answer

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.