Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
960 views
in Technique[技术] by (71.8m points)

r - How to debug methods from Reference Classes?

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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")
  )
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...