[Rd] Reference Classes: getter and setter functions/methods and possible shortcuts

Janko Thyson janko.thyson.rstuff at googlemail.com
Thu May 26 19:12:58 CEST 2011


Hi everyone,

just wanted to ask what's the smartest/recommended way of defining 
getter and setter function *shortcuts* (i.e. something like "[", "[<-") 
for Reference Class objects?
Or is it desired to not use this stuff, but define methods like 
'obj$getSubset(row=1:3, col=1)' and 'obj$setSubset(value=x)' instead?

I have some example code that might help in clarifying what I'm exactly 
after:

setRefClass(
     Class="MyDataFrame",
     fields=list(
         PRIMARYDATA="data.frame"
     ),
     methods=list(
         "subsetGet"=function(
             idx.row,
             idx.col,
             drop=if(missing(idx.row)) TRUE else length(PRIMARYDATA) == 1,
             ...
         ){
             PRIMARYDATA[idx.row, idx.col, drop=drop]
         }
     )
)

setMethod(
     f="initialize",
     signature=signature(.Object="MyDataFrame"),
     definition=function(
         .Object,
         ...,
         row.names=NULL,
         check.rows=FALSE,
         check.names=TRUE,
         stringsAsFactors=default.stringsAsFactors()
     ){
         x.primarydata <- data.frame(..., row.names=row.names,
             check.rows=check.rows, check.names=check.names,
             stringsAsFactors=stringsAsFactors)
         x.generator <- getRefClass(class(.Object))
         x.generator$accessors(names(x.generator$fields()))
         .Object$PRIMARYDATA <- x.primarydata
         return(.Object)
     }
)

myDataFrameCreate <- function(
     ...,
     row.names=NULL,
     check.rows=FALSE,
     check.names=TRUE,
     stringsAsFactors=default.stringsAsFactors(),
     .class.name="MyDataFrame"
){
     out <- getRefClass(.class.name)$new(
         ...,
         row.names=row.names, check.rows=check.rows,
         check.names=check.names,
         stringsAsFactors=stringsAsFactors
     )
     return(out)
}

"[.MyDataFrame" <- function(
     src,
     idx.row,
     idx.col,
     drop=if(missing(idx.row)) TRUE else length(src$PRIMARYDATA) == 1,
     ...
){
     if(!inherits(src, "MyDataFrame")){
         stop("Expecting 'src' to be of class 'MyDataFrame")
     }
     return(src$PRIMARYDATA[idx.row, idx.col, drop=drop])
}

mdf <- myDataFrameCreate(a=1:5, b=1:5)
mdf
mdf$PRIMARYDATA
mdf$getPRIMARYDATA() # automaticall set via 
'getRefClass("MyDataFrame")$accessors()'
mdf$subsetGet(1,1)
mdf$subsetGet(1,)
mdf$subsetGet(,1)
mdf$subsetGet(,1,drop=FALSE)

mdf[1,1]
mdf[1,]
mdf[,1]
mdf[,1, drop=FALSE]

Thanks a lot for any advice,
Janko



More information about the R-devel mailing list