Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:生成setRefClass中所需的元素_R_Class_Reference - Fatal编程技术网

R:生成setRefClass中所需的元素

R:生成setRefClass中所需的元素,r,class,reference,R,Class,Reference,我还是不明白。以下是我想做的: foo <- setRefClass("foo", fields=list(bar="numeric"), methods=list( initialize = function(bar) { bar <<- bar } )) 救命啊 使用RC很难做到这一点,因为您必须始终能够无错误地调用class$new()——许多内部函数都是这样创建对象的。嗯。。。所以基本上是做不到的?这似乎使得在字段中指定类型变得毫无用处:-(这是我的

我还是不明白。以下是我想做的:

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

救命啊

使用RC很难做到这一点,因为您必须始终能够无错误地调用
class$new()
——许多内部函数都是这样创建对象的。嗯。。。所以基本上是做不到的?这似乎使得在
字段中指定类型变得毫无用处:-(这是我的理解,尽管我可能遗漏了一些东西。
> 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
> f1 <- foo$new() # should give an error but does not!
>