3

How to debug a call like getFields? I tried library(debug); mtrace(AB.setFields) but nothing happend.

Besides there are some better ways to define AB.setFields?

AB.getFields<-function(){
  return(list(name,var2))
}
AB.setFields<-function(fields){
  namevar<-names(fields)
  for(i in 1:length(fields)) do.call("<<-",list(namevar[i],fields[[i]]))
}
AB <- setRefClass("AB", fields=c(name="character",
                                 var2="factor"),
                        methods=list(getFields=AB.getFields
                                    ,setFields=AB.setFields)
                  )
a<-AB(name="abc",var2=factor(LETTERS[1:3]))
a$getFields()
fields<-list(name="aaa",var2=factor(1:3))
a$setFields(fields)
a$getFields()
Klaus
  • 1,946
  • 3
  • 19
  • 34
  • Is it possible that you are trying to use "." in a manner that is not supported by R syntactic conventions? – IRTFM Sep 05 '13 at 14:47

1 Answers1

3

You want to call the trace method of the instance object.

a$trace("setFields")

This is the implementation that you want for the setFields method.

AB.setFields <- function(...) {
  dots <- list(...)
  fieldNames <- names(dots)
  for(i in seq_along(dots)) 
  {
    assign(fieldNames[[i]], dots[[i]], attr(.self, ".xData"))
  }
}

a$setFields(name="aaa",var2=factor(1:3))

There's probably some syntactic sugar I've missed to make this prettier, but to get all your fields, you can use

AB.getFields <- function(){
  mget(
    names(.refClassDef@fieldClasses), 
    envir = attr(.self, ".xData")
  )
}
Richie Cotton
  • 118,240
  • 47
  • 247
  • 360
  • Thx, is it also possible to call all member variables at one time from the environment `attr(.self, ".xData")`? Or is the proper way to do this `AB.getFields<-function(){ return(list(name=name,var2=var2)) }`? – Klaus Sep 06 '13 at 09:38
  • Hi, could you please help again, I tried to find out how to trace trace the initialize function, if I instantiate a new object like AB$new(...). I tried AB$trace("initialize") but it doesnt work. – Klaus Sep 11 '13 at 07:07
  • @Klaus: You need to explicitly define an `initialize` method before you can trace it. – Richie Cotton Sep 16 '13 at 11:24