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. Michael Weylandt
2011-Dec-06 21:06 UTC
[R] making changes to global variables in functions
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. Michael 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.