Note: This is separate from, though perhaps similar to, the deparse-substitute trick of attaining the name of a passed argument.
Consider the following situation: I have some function to be called, and the return value
is to be assigned to some variable, say x
.
Inside the function, how can I capture that the name to be assigned to the
returned value is x
, upon calling and assigning the function?
For example:
nameCapture <- function() {
# arbitrary code
captureVarName()
}
x <- nameCapture()
x
## should return some reference to the name "x"
What in R closest approximates captureVarName()
referenced in the example?
My intuition was that there would be something in the call stack to do with
assign()
, where x
would be an argument and could be extracted, but
sys.call()
yielded nothing of the sort; does it then occur internally, and if
so, what is a sensible way to attain something like captureVarName()
?
My notion is that it would act in a similar manner to how the following works, though without the assign()
function, using the <-
operator instead:
nameCapture <- function() sys.call(1)[[2]]
assign("x", nameCapture())
x
# [1] "x"