[R] S4-classes: Assignment of values to slots by reference
Simon Zehnder
szehnder at uni-bonn.de
Fri Mar 1 15:13:41 CET 2013
Dear R-users,
I am working on a project that uses S4-classes. At some point I encountered the problem - well known to R - that I have to pass 3 different objects to a function, that should modify several slots of them and of course there is no passing by reference in R.
Then I read this thread by Steve Lianoglou: https://stat.ethz.ch/pipermail/r-help/2010-August/250468.html, which offers from viewpoint of OOP an elegant solution. But I do not use an Object Method, but a regular function, pass in several objects and modify them.
Here is an example with 1 Object using Steve's approach:
setClass("example",
representation(
par = "matrix",
.cache = "environment")
)
setMethod("initialize", "example", function(.Object, ..., .cache = new.env()) {
callNextMethod(.Object, .cache = .cache, ...)
}
)
ex <- new("example", par = matrix())
fmodify <- function(O1) {
pm <- mean(rnorm(100))
pm <- matrix(pm)
O1 at .cache$par <- pm
}
fmodify(ex)
So far so good. Everything worked nicely. But of course the value computed in the function 'fmodify' is now in the slot ex at .cache$par:
ex at .cache$par
and not in ex at par. Is there a possibility to get it into ex at par?
Best
Simon
More information about the R-help
mailing list