R允许引用类成为引用类的成员

时间:2015-04-21 05:53:25

标签: r reference-class

我试图让“class1”成为“class2”的元素。但是当“class1”具有initialize()函数时,我收到以下错误:

class1 <-
  setRefClass(
    'class1',
    fields = list(attribute1 = 'character'),
    methods = list(
    initialize = function(a){
      attribute1 <<- a
    }
   )
  )

class2 <- 
  setRefClass(
    'class2',
    fields = list(attribute2 = 'class1')
  )
  

.Object $ initialize(...)中的错误:    参数“a”缺失,没有默认值

1 个答案:

答案 0 :(得分:0)

initialize方法提供默认值:

class1 <-
  setRefClass(
    'class1',
    fields = list(attribute1 = 'character'),
    methods = list(
      initialize = function(a = NA_character_){
        attribute1 <<- a
      }
    )
  )

class2 <- 
  setRefClass(
    'class2',
    fields = list(attribute2 = 'class1')
  )
test <- class2()
> test
Reference class object of class "class2"
Field "attribute2":
  Reference class object of class "class1"
Field "attribute1":
  [1] NA