[R] making changes to global variables in functions

R. Michael Weylandt michael.weylandt at gmail.com
Tue Dec 6 22:06:06 CET 2011

No pointer functionality in R (that I know of), but if you want to
return two objects as one the standard way is to put them in a list
and to return that list.


On Tue, Dec 6, 2011 at 2:35 PM, Yev <kirpich at gmail.com> wrote:
> I'm trying to write a function that takes several objects with many
> different attributes and then changes their attributes. So what I wanted to
> happen in the simplified example below is for the function to change the
> attributes of the objects state1 and state2 that are passed to it. But
> because stateA and stateB are local, this isn't working. Are there any easy
> solutions?
> e.g., if I could combine the two objects stateA and stateB into a single
> object, I could return it and then assign it back to objects state1 and
> state2. Or if I could pass a pointer to the original object.. But I cannot
> find an easy way of doing either.  Thanks in advance..
> state1 <- list(n=100, won=0)
> state2 <- list(n=100, won=0)
> fight2 <- function(stateA, stateB){
>   stateA$n <- 50
>   stateB$n <-50
> }
> fight2(state1,state2)
> state1$n
> state2$n
>        [[alternative HTML version deleted]]
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list