Accessing data in sp objects
It's quite unusual to know exactly the indices of elements you want to keep, and far more likely you want to subset based on data attributes. You've seen the data associated with a Spatial___DataFrame lives in the data slot, but you don't normally access this slot directly.
Instead,$ and [[ subsetting on a Spatial___DataFrame pulls columns directly from the data frame. That is, if x is a Spatial___DataFrame object, then either x$col_name or x[["col_name"]] pulls out the col_name column from the data frame. Think of this like a shortcut; instead of having to pull the right column from the object in the data slot (i.e. x@data$col_name), you can just use x$col_name.
Let's start by confirming the object in the data slot is just a regular data frame, then practice pulling out columns.
This exercise is part of the course
Visualizing Geospatial Data in R
Exercise instructions
- Call
head()andstr()(one at a time) on thedataslot ofcountries_spdf. Verify that this object is just a regular data frame. - Pull out the
namecolumn ofcountries_spdfusing$. - Pull out the
subregioncolumn ofcountries_spdfusing[[.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Call head() and str() on the data slot of countries_spdf
# Pull out the name column using $
# Pull out the subregion column using [[