0

1) I cant figure out where the Error:

Error in args[[1]] : subscript out of bounds

comes from, if I try to run the folowing code:

Part.initialize<-function(...){
  args<-list(...)

    .self$var1 <- if(is.null(args[["var1"]])) vector() else args[["var1"]]
    .self$var2 <- if(is.null(args[["var2"]])) character() else as.character(args[["var2"]])
    .self
}

Part<-setRefClass(Class = "Part"
                 ,fields = c(var1 = "ANY", var2 = "character")
                 ,methods = list(initialize=Part.initialize))

A.initialize<-function(...){
  args<-list(...)

  .self$var1 <- if(is.null(args[["var1"]])) vector() else args[["var1"]]
  .self$var2 <- if(is.null(args[["var2"]])) character() else as.character(args[["var2"]])
  .self$var3 <- if(is.null(args[["var3"]])) list() else as.list(args[["var3"]])
  .self  
}

A<-setRefClass(Class = "A"
              ,contains = "Part"
              ,fields = list(var3 = "list")
              ,methods = list(initialize=A.initialize))

2) Is it possible to organize the code in that way that I have to add only one line

.self$var3 <- if(is.null(args[["var3"]])) list() else as.list(args[["var3"]])

for the initialize function in class A and the rest comes from the father class Part?

Klaus
  • 1,946
  • 3
  • 19
  • 34

1 Answers1

1

Use named arguments rather than parsing ...; make sure that the default constructor works when invoked with no arugments

Part.initialize<-function(..., var1=vector(), var2=character()){
    callSuper(..., var1=var1, var2=as.character(var2))
}

Part<-setRefClass(Class = "Part"
                 ,fields = c(var1 = "ANY", var2 = "character")
                 ,methods = list(initialize=Part.initialize))

Only interpret arguments for the class under consideration

A.initialize<-function(..., var3=list()){
    callSuper(..., var3=as.list(var3))
}

A<-setRefClass(Class = "A"
               ,contains = "Part"
               ,fields = list(var3 = "list")
               ,methods = list(initialize=A.initialize))

Simple test cases

Part()
A()
A(var3=list(a=1))
Martin Morgan
  • 45,935
  • 7
  • 84
  • 112
  • Many thanks, what can I do if I want to use a general initialize methode `generic.initialize<-function(...){ args <- list(...); map <- .self$getRefClass()$fields(); idx <- names(args) %in% names(map); validArgs<- args[idx]; map <- map[map != "ANY"]; idx <- names(validArgs) %in% names(map); validArgs[idx] <- Map(as, validArgs[idx], map[names(validArgs)[idx]]); do.call(.self$initFields, validArgs); #do.call(callSuper,args[!(names(args)%in%names(validArgs))]); }` – Klaus Sep 23 '13 at 09:11
  • How can I call callSuper, if both classes should use the same initialize function above? – Klaus Sep 23 '13 at 14:17