You don't need to provide the name as an extra argument; substitute
will get that for you. To do things in the scope of the calling function you use eval
with parent.frame
.
f <- function(x) {
eval(substitute( x[1,] <- c(1,2,3) ), parent.frame())
}
Then,
m <- c(2,5,3,7,1,3,9,3,5)
> dim(m) <- c(3,3)
> m
[,1] [,2] [,3]
[1,] 2 7 9
[2,] 5 1 3
[3,] 3 3 5
> f(m)
> m
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 5 1 3
[3,] 3 3 5
That said, modifying the caller's environment is generally a bad idea and it will usually lead to less confusing/fragile code if you just return the value and re-assign it to m
instead. This is generally preferable.:
f <- function (x) {
x[1,] <- c(1,2,3)
x
}
m <- f(m)
However, I have occasionally found eval
shenanigans to come in handy when I really needed to change an array in place and avoid an array copy.