modify variable within R function

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

提交回复
热议问题