S4课程:传递给new()的参数不会进入他们的插槽

时间:2015-05-31 20:06:57

标签: r new-operator s4 slots

我正在构建一个包含S4类的R包,而我在使用new函数时遇到了问题。我有一个名为Configs

的班级
setClass("Configs", 
  slots = list(
    burnin = "numeric",
    chains = "numeric",
    features = "numeric",
    iterations = "numeric",
    mphtol = "numeric",
    samples = "numeric",
    seed = "numeric",
    thin = "numeric",
    verbose = "numeric"
  ),
  prototype = list(
    burnin = 0,
    chains = 2,
    features = 5,
    iterations = 5,
    mphtol = 1e-4,
    samples = 3,
    seed = sample(1e6, 1),
    thin = 0,
    verbose = 0
  )
)

当我将此部分加载到我的全局环境中时,我可以使用不同于默认值的插槽创建一个新的Configs对象。

> new("Configs", features = 1000)
An object of class "Configs"
Slot "burnin":
[1] 0

Slot "chains":
[1] 2

Slot "features":
[1] 1000

Slot "iterations":
[1] 5

Slot "mphtol":
[1] 1e-04

Slot "samples":
[1] 3

Slot "seed":
[1] 437211

Slot "thin":
[1] 0

Slot "verbose":
[1] 0

但是,当我安装整个软件包时,将其加载到一个新环境中,然后运行new("Configs", features = 1000),我得到features为5.为什么没有new()放置插槽中的值了吗?

我的包传递了R CMD check,没有任何错误,警告或注释。这是我的会话信息。

> sessionInfo()
R version 3.2.0 (2015-04-16)
Platform: x86_64-unknown-linux-gnu (64-bit)
Running under: CentOS release 6.6 (Final)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] heterosis_0.0  pracma_1.8.3   MCMCpack_1.3-3 MASS_7.3-40    coda_0.17-1   

loaded via a namespace (and not attached):
[1] tools_3.2.0     grid_3.2.0      lattice_0.20-31

编辑:我明白了,但我还是不满意。

事实证明我的initialize功能导致了问题。

setMethod("initialize", "Configs", function(.Object, ...){ 
#  .Object = new("Configs", ...)
  validObject(.Object)      
  return(.Object)
})

当我删除它时,new会再次将内容放入插槽中。我很高兴我发现了这个问题,但我不想完全删除我的初始化功能。我想要一种方便的方法来调用validObject并进行其他错误检查,initialize似乎是一个合适且适当的地方。如果我取消注释注释行,我会得到无限递归。如何在不破坏new的情况下创建构造函数?

1 个答案:

答案 0 :(得分:6)

initialize()是两用的 - 初始化和复制构造。提供显式构造函数

通常更好(也为用户提供更多信息)
.A = setClass("A", representation(x="numeric"))

A = function(x=numeric(), ...)
    .A(x=x, ...)
当对象创建涉及插槽分配时,默认初始化方法调用

validOjbect(),因此在您自己的初始化方法期间无需显式调用它(见下文);也许你有

.A = setClass("A", representation(x="numeric"),
    prototype=prototype(x=NA_integer_))

setValidity("A", function(object) {
    if (length(object@x) != 1L)
        "'x' must be length 1"
    else TRUE
})

A = function(x=NA_integer_, ...)
    ## signature is informative -- 'x' is integer(1), not just '...'
    ## coercion (e.g., as.integer(), below) and other set-up
    new("A", x=as.integer(x), ...)

> A()
An object of class "A"
Slot "x":
[1] NA

> A(x=1)
An object of class "A"
Slot "x":
[1] 1

> A(x=1:2)
Error in validObject(.Object) : 
  invalid class "A" object: 'x' must be length 1

一个重要的警告是,当用户没有初始化插槽时,有效方法被调用,因此必须定义prototype()以创建有效对象(验证这一点)与validObject(new("A"))

对于您的问题,有效性函数是进行“其他错误检查”的正确位置。编写正确的初始化方法非常困难,但更接近正确的是

.B = setClass("B",
    representation(x="numeric", y="numeric"),
    prototype=prototype(x=NA_integer_, y=NA_real_))
setMethod("initialize", "B", 
    function(.Object, ..., x=.Object@x, y=.Object@y)
{
    ## pre-processing, then invoke 'next' initialize() method
    ## base initialize() creates the object then calls validObject()
    ## so no need for explicit test of validity
    .Object <- callNextMethod(.Object, ..., x=x, y=y)
    ## post-processing
    .Object
})

这种奇怪的结构允许initialize()继续表现为复制构造函数

> b = new("B", x=1, y=2)    # constructor
> initialize(b, x=2)        # copy-constructor
An object of class "B"
Slot "x":
[1] 2

Slot "y":
[1] 2

在类继承期间很重要。但正如你所看到的那样,这是非常棘手的 - 最终它真的很难,很少值得努力让initialize()正确。

请注意,我们尚未完全履行initialize()

的合同
setClass("C", representation(x="numeric", y="numeric"))  # default initialize()

在使用new()

调用时实际上充当复制构造函数
> c = new("C", x=1, y=2)
> new("C", c, x=2)
An object of class "C"
Slot "x":
[1] 2

Slot "y":
[1] 2

与B的实施没有复制结构

> b = new("B", x=1, y=2)
> new("B", b, x=2)
An object of class "B"
Slot "x":
[1] 2

Slot "y":
[1] NA