M. Beausoleil M. Beausoleil - 1 month ago 10
R Question

What is the difference between extraction via $ and @ in R?

I wonder what is the difference between the "component/slot extraction" (via

?Syntax
) operators
$
(dollar sign) and
@
(at symbol) in R.

Here's an example with
$
:

yo=data.frame(c(1:10), c(rnorm(10,0,1)))
yo$c.1.10.


prints:

[1] 1 2 3 4 5 6 7 8 9 10


 

yo@c.1.10.
Error: trying to get slot "c.1.10." from an object (class "data.frame") that is not an S4 object


Here's an example with
@
:

setClass("track", representation(x="numeric", y="numeric"))
myTrack <- new("track", x = -4:4, y = exp(-4:4))
myTrack@x


prints:

[1] -4 -3 -2 -1 0 1 2 3 4


 

myTrack$x
Error in myTrack$x : $ operator not defined for this S4 class


In either case, why does one work and not the other?

Another example is the following from the
SoDA
package in R, in the function
geoXY
:

library(SoDA)
xy <- geoXY(gpsObject1@latitude, gpsObject1@longitude, unit = 1000)
plot(xy[,1], xy[,2], asp = 1)

Answer

I don't see anything in the R Language defenition about this (via this question),

But the difference is basically: @ is for S4 objects, $ is for lists.

That may be a bit abstract, so if you're wondering about what to use for a given object, just look at str, e.g.:

str(yo)
# 'data.frame': 10 obs. of  2 variables:
#  $ c.1.10.           : int  1 2 3 4 5 6 7 8 9 10
#  $ c.rnorm.10..0..1..: num  -0.536 -0.453 -0.599 1.134 -2.259 ...

We can see $ here, so $ is what to use.

Alternatively,

str(myTrack)
# Formal class 'track' [package ".GlobalEnv"] with 2 slots
#   ..@ x: int [1:9] -4 -3 -2 -1 0 1 2 3 4
#   ..@ y: num [1:9] 0.0183 0.0498 0.1353 0.3679 1 ...

Here, we see @, so @ is what to use.

This can get even more confusing when an S4 object has a list in one of its slots (what comes to mind first for me is a SpatialPolygonsDataFrame, where a column in the can be accessed via spdf@data$column)

Perhaps see also ?slot which gives a bit more detail as relates to @, ?isS4 for an alternative to str to tell you whether @ can be expected to work with an object, or the Chapter of Hadley Wickham's book on S4 objects for more on S4 in general.