Slightly embarrassed to ask such a simple question but I’ve wasted an hour now and figure its a 30 second solution. The problem is how to edit an existing object that is provided as an input to a function. I’ve also played with the super-assignment <<- without success.
The example function uses 2 inputs (one for an object and one for its name). I just need a form of this that removes the need for the ‘n’ input.
m <- c(2,5,3,7,1,3,9,3,5)
dim(m) <- c(3,3)
m
f <- function(x, n) { # where 'n' is the object name of 'x'
x[1,] <- c(1,2,3)
assign(n, x, envir = .GlobalEnv)
}
f(m, 'm')
m
Thanks in advance.
You don’t need to provide the name as an extra argument;
substitutewill get that for you. To do things in the scope of the calling function you useevalwithparent.frame.Then,
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
minstead. This is generally preferable.:However, I have occasionally found
evalshenanigans to come in handy when I really needed to change an array in place and avoid an array copy.