[R] Call by reference: Was: Object orientation?

Henrik Bengtsson henrikb at braju.com
Thu Mar 22 05:10:05 CET 2001


To reply to Yves Gauvreau question (Jan 24, 2001) about how to set values
within function, it is possible to do without without using the "<<-"
assignment operator or other nasty tricks. I had the same problem and I did
a nasty workaround two weeks ago implementing the functionality of reference
variables, but today I "ran into" the [R] help page for ".Alias". With
.Alias one can immitate call by reference! Here is an example that shows how
it works:

Foo <- function(value=0) {
  this <- list(
    value = value
  )
  class(this) <- "Foo";
  return(this);
}

set <- function(object, value) {
  this <- .Alias(object);
  this$value <- value;
  return (invisible());
}

get <- function(object) {
  return (object$value);
}

a <- Foo();
b <- Foo(10);

cat("a =", get(a), "\n");  # a = 0
cat("b =", get(b), "\n");  # b = 10

set(a, 10);
set(b, 20);

cat("a =", get(a), "\n");  # a = 10
cat("b =", get(b), "\n");  # b = 20

Have a nice day

Henrik Bengtsson

PhD Student in Statistics
Lund University & UC Berkeley
henrikb at braju.com

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list