通过$和@在R中提取有什么区别?

M. *_*eil 11 r

我想知道R中"组件/插槽提取"(via ?Syntax)运算符$(美元符号)和@(符号)之间的区别是什么.

这是一个例子$:

yo=data.frame(c(1:10), c(rnorm(10,0,1)))
yo$c.1.10.
Run Code Online (Sandbox Code Playgroud)

打印:

 [1]  1  2  3  4  5  6  7  8  9 10
Run Code Online (Sandbox Code Playgroud)

 

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

这是一个例子@:

setClass("track", representation(x="numeric", y="numeric"))
myTrack <- new("track", x = -4:4, y = exp(-4:4))
myTrack@x
Run Code Online (Sandbox Code Playgroud)

打印:

[1] -4 -3 -2 -1  0  1  2  3  4
Run Code Online (Sandbox Code Playgroud)

 

myTrack$x
Error in myTrack$x : $ operator not defined for this S4 class
Run Code Online (Sandbox Code Playgroud)

在任何一种情况下,为什么一个工作而不是另一个?

另一个例子是SoDAR中的包中的以下函数geoXY:

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

Mic*_*ico 13

我没有看到R语言对此的任何修改(通过这个问题),

但差别基本上是:@对于S4对象,$是用于列表(包括许多S3对象).

这可能有点抽象,所以如果你想知道给定对象使用什么,只需看看str,例如:

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 ...
Run Code Online (Sandbox Code Playgroud)

我们可以$在这里看到,$使用的是什么.

或者,

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 ...
Run Code Online (Sandbox Code Playgroud)

在这里,我们看到@,@使用的是什么.

当一个S4对象在其中一个插槽中有一个列表时,这会变得更加混乱(我首先想到的是a SpatialPolygonsDataFrame,data可以通过插槽访问插槽中的列spdf@data$column)

也许还?slot可以看到哪个更详细@,?isS4因为它str可以告诉你是否@可以预期与对象一起工作,或者哈德利威克姆关于S4对象的书章节更多关于S4.