for a subset of SpatialPolygonsDataFrame? When I have a SpatialPolygonsDataFrame object, I know I can get the data in two w...">

Why can you use `$` for a subset of SpatialPolygonsDataFrame?

When I have a SpatialPolygonsDataFrame object, I know I can get the data in two ways:

spatial_df@data$column
spatial_df$column

      

However, I don't understand why the second way is possible. I thought I should be able to access the slot data

using @

? Is this something unique about the class SpatialPolygonsDataFrame

, or is it something about the S4 object in general?

One possible answer is in the docs sp

which mentions a method [

for a class SpatialPolygonsDataFrame

. However, since it is $

equivalent [[

to NOT to [

, I'm not sure what the answer is.

+3


source to share


1 answer


The short answer is that this behavior $

is implemented by a class Spatial

in a package sp

and is not a sign of a generic S4 object.

Long answer (how do I know about this):

  • Use showMethods("$")

    to learn about all common methods $

    .
The result shows:
Function: $ (package base)
x="C++Class"
x="envRefClass"
x="Module"
x="Raster"
x="refObjectGenerator"
x="Spatial"
x="SpatialGDAL"
x="SpatialPoints"
x="SpatialPolygonsDataFrame"
    (inherited from: x="Spatial")

      



So, we know what SpatialPolygonsDataFrame-class

inherits $

from Spatial-class

. Let's go to the root:

  • getMethod("$", "Spatial")

    which shows the implementation $

    for Spatial-class

    as follows:
Method Definition:

function (x, name) 
{
    if (!("data" %in% slotNames(x))) 
        stop("no $ method for object without attributes")
    x@data[[name]]
}
<environment: namespace:sp>

      

Hence, spatial_df$col_name

is a shortcut forspatial_df@data[["col_name"]]

+6


source







All Articles