2

I want to pass a matrix into a function and save its modifying within function, how can I pass it by reference like C++ or java?

2 Answers2

1

See:

?ReferenceClasses

The below is a hack that could cause a lot of confusion:

f <- function(x, ...) {
    name <- deparse(substitute(x))
    x <- x + 1
    assign(name, x, envir=parent.frame())
    return(invisible())
}
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
1

You can use eval.parent and substitute.

> my_fun <- function(x, value){
+     eval.parent(substitute(x<-value))
+ }

> k = 1
> my_fun(k, 100)
> k
[1] 100
Qiang Kou
  • 522
  • 4
  • 8