In addition to the other answers here that actually pass your object by reference ( environment objects and Reference Classes), if you are just interested in a call-link for syntactic convenience (i.e. you are not against your data copied inside), you can emulate this by assigning the final value back to an external variable when returning:
byRef <- function(..., envir=parent.frame(), inherits=TRUE) { cl <- match.call(expand.dots = TRUE) cl[c(1, match(c("envir", "inherits"), names(cl), 0L))] <- NULL for (x in as.list(cl)) { s <- substitute(x) sx <- do.call(substitute, list(s), envir=envir) dx <- deparse(sx) expr <- substitute(assign(dx, s, envir=parent.frame(), inherits=inherits)) do.call(on.exit, list(expr, add=TRUE), envir=envir) } }
Then we can declare the arguments "on call":
f <- function(z1, z2, z3) { byRef(z1, z3) z1 <- z1 + 1 z2 <- z2 + 2 z3 <- z3 + 3 c(z1, z2, z3) } x1 <- 10 x2 <- 20 x3 <- 30
Please note: if you access variables “by reference” by their external names ( x1 , x3 ) anywhere inside the function, you will receive their unchanged values from the outside. In addition, this implementation simply treats variable names as arguments, so indexed arguments like f(x[1], ...) will not work (although you could probably implement this with a bit more complicated manipulation with expressions to get around the limited assign ).
codeola Feb 20 '14 at 7:06 2014-02-20 07:06
source share