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

lan*_*dau 5 r new-operator slots s4

我正在用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
  )
)
Run Code Online (Sandbox Code Playgroud)

当我将这部分加载到我的全局环境中时,我可以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
Run Code Online (Sandbox Code Playgroud)

但是,当我安装整个软件包时,将其加载到一个新的环境中,并运行new("Configs", features = 1000),我得到一个features5.为什么不再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
Run Code Online (Sandbox Code Playgroud)

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

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

setMethod("initialize", "Configs", function(.Object, ...){ 
#  .Object = new("Configs", ...)
  validObject(.Object)      
  return(.Object)
})
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*gan 6

initialize()是两用的 - 初始化和复制构造.提供显式构造函数通常更好(也为用户提供更多信息)

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

A = function(x=numeric(), ...)
    .A(x=x, ...)
Run Code Online (Sandbox Code Playgroud)

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

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

一个重要的警告是,当用户没有初始化插槽时,不会调用有效性方法,因此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
})
Run Code Online (Sandbox Code Playgroud)

这种奇怪的结构允许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
Run Code Online (Sandbox Code Playgroud)

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

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

setClass("C", representation(x="numeric", y="numeric"))  # default initialize()
Run Code Online (Sandbox Code Playgroud)

当调用时,它实际上充当复制构造函数 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
Run Code Online (Sandbox Code Playgroud)

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