R:在setRefClass中创建一个元素

时间:2014-05-13 13:57:54

标签: r class reference

我仍然没有得到它。这就是我想要做的事情:

foo <- setRefClass("foo", fields=list(bar="numeric"), methods=list(
  initialize = function(bar) {
     bar <<- bar
  }
))

换句话说:

  • bar必须为数字
  • bar必须在开头设置
  • bar不得具有默认值

可是:

> f1 <- foo$new(bar=1)
> f1$copy()
Error in .Object$initialize(...) : 
  argument "bar" is missing, with no default

好的,怎么样:

foo <- setRefClass("foo", fields=list(bar="numeric"), methods=list(
  initialize = function(bar=NULL) {
      bar <<- bar
 }

))

都能跟得上:

> f1 <- foo$new(bar=1)
> f1$copy()
 Error: invalid assignment for reference class field ‘bar’, should be from class “numeric” or a subclass (was class “NULL”) 

如果我这样做:

foo <- setRefClass("foo", fields=list(bar="numeric"), methods=list(
     initialize = function(bar=NULL) {
         if (! missing(bar) && is.numeric(bar)) bar <<- bar
     }
))

然后这很好:

> f1 <- foo$new(bar=1)
> f1$copy()
Reference class object of class "foo"
Field "bar":
[1] 1

但我不再对bar进行创建时检查:

> f1 <- foo$new() # should give an error but does not!
>

帮助!

0 个答案:

没有答案