Reputation: 371
I need to do pass by reference in R by R studio on win 7.
My code:
library(hash)
myfunc<-function(myhash.arg)
{
myhash <- myhash.arg
if (!has.key("first", myhash))
myhash["first"] <- list()
alist <- myhash["first"]
alist <- append(alist, 9)
eval.parent(substitute(myhash.arg<-myhash))
return(0)
}
ahash<-hash()
for(i in 1:5)
{
myfunc(myhash.arg = ahash)
print(c("length of ahash is ", length(ahash)))
print(c("length of ahash list is ", length(ahash["first"])))
}
but, the list size is always 1, the appended elements are missed.
Upvotes: 0
Views: 113
Reputation: 3462
Exapnding on my comment above here is a generic, but ugly, way to pass things "by reference" in R. suppose you have an object named h in environment e and you want to pass it to function f by reference. you'd like something like this:
f = function(object) {
...
# assign something into object or manipulate it
...
}
f(h)
# now you want to see that h has changed.
Doing it in the above way would not change your object, but the following code will do:
f = function(env,obj.name) {
...
# the assignment is done as follows
env[[obj.name]] = ...
...
}
f(e,"h")
# now h is changed
for example:
h = list(a=1,c=2)
f = function(e,n) {
e[[n]]$c = 5
return(0)
}
f(.GlobalEnv,"h")
h
that's it.
Now you can adapt it to your case
I use this method a lot when I have big datasets. I still want to organize my work in functions that operate on the dataset (for example, to make my analysis reproducible, or to be able to do the same analysis on different subsets, etc.), but for performance issues copying the dataset is a problem. so I create an environment called "working.data", and pass only the names of the data.frames to my functions. I even hard code the name of the data environemtn (so I don't need to pass it), and deal with the naming/renaming of environment outside the functions. I am not sure I'd recommend the latter bit of my solution.
Upvotes: 1