0

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"
jcai849
  • 13
  • 3
  • I'm confused as to what you mean. you want, somehow, the function to know what the variable name you might assign its output to is? – morgan121 May 29 '20 at 03:19
  • Can you use `deparse(substitute` – akrun May 29 '20 at 03:19
  • 1
    Just curious, what do you want `nameCapture()` to return if it is called on its own, without assignment? Or as part of a larger call, like `x <- c("hello", nameCapture(), "world")`? – Gregor Thomas May 29 '20 at 03:25
  • @RAB yes, dynamically as it is called. – jcai849 May 29 '20 at 03:32
  • @GregorThomas perhaps it would return NULL if not assigned. In the larger call, ideally the name it would be assigned to ("x" in your second case). But I'm not necessarily after the generality required by a call larger than a singular call – jcai849 May 29 '20 at 03:39

0 Answers0