modify variable within R function

前端 未结 5 697
孤城傲影
孤城傲影 2020-12-03 05:40

How do I modify an argument being passed to a function in R? In C++ this would be pass by reference.

g=4
abc <- function(x) {x<-5}
abc(g)
相关标签:
5条回答
  • 2020-12-03 05:58

    Am I missing something as to why you can't just do this?

    g <- abc(g)
    
    0 讨论(0)
  • 2020-12-03 06:02

    I have a solution similar to @Dason's, and I am curious if there are good reasons not to use this or if there are important pitfalls I should be aware of:

    changeMe = function(x){
    assign(deparse(substitute(x)), "changed", env=.GlobalEnv)
    }   
    
    0 讨论(0)
  • 2020-12-03 06:03

    There are ways as @Dason showed, but really - you shouldn't!

    The whole paradigm of R is to "pass by value". @Rory just posted the normal way to handle it - just return the modified value...

    Environments are typically the only objects that can be passed by reference in R.

    But lately new objects called reference classes have been added to R (they use environments). They can modify their values (but in a controlled way). You might want to look into using them if you really feel the need...

    0 讨论(0)
  • 2020-12-03 06:14

    There has got to be a better way to do this but...

    abc <- function(x){eval(parse(text = paste(substitute(x), "<<- 5")))}
    g <- 4
    abc(g)
    g
    

    gives the output

    [1] 5
    
    0 讨论(0)
  • 2020-12-03 06:22

    I think that @Dason's method is the only way to do it theoretically, but practically I think R's way already does it.

    For example, when you do the following:

    y <- c(1,2)
    x <- y
    

    x is really just a pointer to a the value c(1,2). Similarly, when you do

    abc <- function(x) {x <- 5; x}
    g <- abc(g)
    

    It is not that you are spending time copying g to the function and then copying the result back into g. I think what R does with the code

    g <- abc(g)
    

    is:

    1. The right side is looked at first. An environment for the function abc is set up.
    2. A pointer is created in that environment called x.
    3. x points to the same value that g points to.
    4. Then x points to 5
    5. The function returns the pointer x
    6. g now points to the same value that x pointed to at the time of return.

    Thus, it is not that there is a whole bunch of unnecessary copying of large options.

    I hope that someone can confirm/correct this.

    0 讨论(0)
提交回复
热议问题