这几乎是一个哲学问题:直接使用访问和/或设置 S4 对象的插槽是否不好@
?
我一直被告知这是不好的做法,用户应该使用“访问器”S4 方法,并且开发人员应该为他们的用户提供这些方法。但我想知道是否有人知道这背后的真正交易?
这是一个使用sp
包的示例(但可以推广到任何 S4 类):
> library(sp)
> foo <- data.frame(x = runif(5), y = runif(5), bar = runif(5))
> coordinates(foo) <- ~x+y
> class(foo)
[1] "SpatialPointsDataFrame"
attr(,"package")
[1] "sp"
> str(foo)
Formal class 'SpatialPointsDataFrame' [package "sp"] with 5 slots
..@ data :'data.frame': 5 obs. of 1 variable:
.. ..$ bar: num [1:5] 0.621 0.273 0.446 0.174 0.278
..@ coords.nrs : int [1:2] 1 2
..@ coords : num [1:5, 1:2] 0.885 0.763 0.591 0.709 0.925 ...
.. ..- attr(*, "dimnames")=List of 2
.. .. ..$ : NULL
.. .. ..$ : chr [1:2] "x" "y"
..@ bbox : num [1:2, 1:2] 0.591 0.155 0.925 0.803
.. ..- attr(*, "dimnames")=List of 2
.. .. ..$ : chr [1:2] "x" "y"
.. .. ..$ : chr [1:2] "min" "max"
..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slots
.. .. ..@ projargs: chr NA
> foo@data
bar
1 0.6213783
2 0.2725903
3 0.4458229
4 0.1743419
5 0.2779656
> foo@data <- data.frame(bar = letters[1:5], baz = runif(5))
> foo@data
bar baz
1 a 0.22877446
2 b 0.93206667
3 c 0.28169866
4 d 0.08616213
5 e 0.36713750