CommencerCommencer gratuitement

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.

Cet exercice fait partie du cours

Visualizing Geospatial Data in R

Afficher le cours

Instructions

  • Call head() and str() (one at a time) on the data slot of countries_spdf. Verify that this object is just a regular data frame.
  • Pull out the name column of countries_spdf using $.
  • Pull out the subregion column of countries_spdf using [[.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

# Call head() and str() on the data slot of countries_spdf



# Pull out the name column using $


# Pull out the subregion column using [[
Modifier et exécuter le code