[R] Call by reference or suggest workaround
Duncan Murdoch
murdoch.duncan at gmail.com
Sat Jun 19 16:53:29 CEST 2010
On 19/06/2010 10:32 AM, Chidambaram Annamalai wrote:
> I have written code to compute multi-indices in R [1] and due to the
> recursive nature of the computation I need to pass around the *same*
> matrix object (where each row corresponds to one multi-index). As pass
> by reference wasn't the default behavior I declared a global matrix
> (mat) and used the <<- operator to write to the global matrix. So the
> usage would be to call genMultiIndices(3,2) for side effects to
> generate all multi-indices of length 3 and sum 2. And then access the
> global matrix.
>
> However, after coding this I can't seem to export the global matrix
> object (in the NAMESPACE file) and still retain mutability since its
> binding is "locked" (R throws an error). Can I somehow unlock this?
>
> Ideally I would want to pass around the same matrix to the recursive
> function. Is that possible? If not, could someone please suggest a
> workaround to use the code in an R package?
If you pass the object to multiple functions it will only create a new
copy when necessary due to modifying it, so the cost of passing it down
to every recursive call is not so large as you seem to think. But it's
not zero cost, passing arguments to functions costs a little bit.
You can avoid this using nested functions and <<- as you had before.
That is, instead of making your recursive function a top level function
so that <<- assigns into the namespace environment (which is what's
causing the error), make it a nested function within another, and do
your assignments to the outer frame. For example,
outer <- function(args) {
mat <- matrix(NA, 3,3)
recursive <- function() {
mat <<- newvalue # does the assignment into outer's frame
if (!stop) recursive()
}
}
Duncan Murdoch
More information about the R-help
mailing list