[R] Modify objects in function
Simon Zehnder
szehnder at uni-bonn.de
Thu Jan 31 12:52:22 CET 2013
Dear R community,
I do know, that an R function is constructing a copy of any object passed as argument into a function. I program on a larger S4 project for a package, and I arrived at a point where I have to think a little harder on implementation style (especially to spare users complex object handling).
I have a function foo(), taking as input arguments two S4 objects of different class type
foo <- function(o1, o2) {
o1 at att1 <- producesomething()
o2 at att2 <- producesomethingelse()
}
Of course, this functions does not change the objects in the global environment. Now I have two choices
1. Change the objects and return a list with both objects:
foo <- function(o1, o2) {
o1 at att1 <- producesomething()
o2 at att2 <- producesomethingelse()
l <- list(O1 = o1, O2 = o2)
return(l)
}
This is cumbersome for users, as they have then to assign the objects inside the returned list to the symbols used in the global environment. But it is the way intended by R.
2. Change the objects of the global environment inside the function:
foo <- function(o1, o2) {
o1 at att1 <- producesomething()
o2 at att2 <- producesomethingelse()
assign("o1", o1, .GlobalEnv)
assign("o2", o2, .GlobalEnv)
}
This is for users very practical, as the symbols used before refer now to objects with changed attributes and can be used immediately. BUT: It is not intended to be done like this.
I spared any solution using one function for every single object type, as this becomes even more cumbersome than choice 1 above, in my opinion.
What is your opinion on the trade-off between user-friendly handling of objects and R-intended programming style? Do I miss another choice, combining both?
Best
Simon
More information about the R-help
mailing list