Given a prototypical list of elementary R data
it is trivial but tedious to define a valid
S4 class with appropriate getter and setter methods.
DrS4's ClassSupport
class helps with this.
Stuart Lee's blog post on S4
inspires the default
parameter settings in the clgen
function.
suppressPackageStartupMessages(library(DrS4)) args(clgen)
Try it:
tt = clgen() tt
Learn a little more about this infrastructure:
getClass(class(tt))
We dump the code defining the class and its get/set methods.
dumpcs(tt)
To use the code, we can source it, or place in a package.
tf = tempfile() dumpcs(tt, tf) source(tf) tur = new("Turtle") tur path(tur) path(tur) = matrix(c(1,1), nr=1) tur
Stuart showed how a more functional turtle can be defined -- one that holds a pen. We'll need a new definition and new getters and setters.
We defined a method
on our ClassSupport
class to
produce the new class.
newprops = list(colour = "pink", thickness = 1, on = FALSE) nn = extendClassSupport(tt, newprops, "TurtleWithPen") nn dumpcs(nn)
We can now source that code to allow composition of methods for TurtleWithPen.
There is something unsavory about this approach to code generation. I produced it in the face of a task involving a configuration object that seems to require many slots. I wanted to avoid the temptation to use simple functions and the at sign. My hope is that programs along the lines of those demonstrated here will help lower the barrier to adoption of formal class and method definitions in R programming. There are surely many improvements to be made in what has been proposed here.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.