0

This is an extension of the previous post In R, how to get an object's name after it is sent to a function? and its also popular duplicate How to convert variable (object) name into String [duplicate]

The idea is that you have a list of parameter values, e.g.

parameters <- c(parameter1,parameter2,...)

and you want to write to a file the parameter name (the variable) and value, e.g

parameter1:  500
parameter2:  1.2
...

In the previous posts we saw this function:

getVariablesName <- function(variable) { 
  substitutedVariable <- substitute(variable); 
  if (length(substitutedVariable) == 1) {
    deparse(substitutedVariable)
  }  else {
    sub("\\(.", "", substitutedVariable[2]) 
  }

}

which is capable of recalling the passed variable's "name"

getVariablesName(foo)
'foo'

but when a variable is passed twice, we loss this information, e.g.

logThis <- function(thingsToLog, inThisFile) {
  for (thing in thingsToLog) {
    write(paste(getVariablesName(thing),":\t",thing),
                         file = inThisFile,
                         append = TRUE)
  }
}

the idea being to pass logThis(c(parameter1,parameter2,...), "/home/file.txt")

So how can we retain the variables' "names" as they get encapsulated in a vector, passed to the function logThis and then looped through?

Community
  • 1
  • 1
SumNeuron
  • 4,850
  • 5
  • 39
  • 107
  • I think this is a equivalent to asking for access to the names of objects inside functions used with `lapply`. There no names there. Only copies of the values get passed. If you gave named objects as the value for thingsToLog you can get them to be written. – IRTFM Oct 30 '16 at 16:53
  • @42- I was thinking that might have to be the case, but that isn't very elegant. Who wants to make an object more complex simply for the purpose of writing out its name... – SumNeuron Oct 30 '16 at 16:55

0 Answers0