modify variable within R function

前端 未结 5 699
孤城傲影
孤城傲影 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 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.

提交回复
热议问题