[R] Extracting list names within a looped function

Gaj Stan (BIGCAT)
Thu, 15 Nov 2012 10:14:54 -0000

Hello all,

I have the following problem:

1) A list was defined as 'a'

a <- list("var1"=c(100:1), "var2"=c(1:100),
"var3"=rnorm(100))

2) a function 'foo' was defined that extracts the variable name assigned
to x using the deparse(substitute()) functionality. This name will then be used
within the function to generate specific output files, etc.

foo <- function(x) {
  print( deparse(substitute(x)) )
}

However, I am currently interested in looping through all list variables and
extract the list variable name from within the function. The current loop (see
below) will result in

for(i in 1:length(a)) {
  foo(a[[i]])
}
[1] "a[[i]]"

which actually does what I expected of deparse(substitute(x)), but is not what I
wanted. I would like to end up with something like

[1] "var1"
[1] "var2"
[1] "var3"

or

[1] "a[[\"var1\"]]"
[1] "a[[\"var2\"]]"
[1] "a[[\"var3\"]]"

Keep in mind that x has to be a matrix, and not a list. This to keep the
function as general as possible.

Does anyone have any idea on how to tackle this? Is deparse(substitute(x)) here
the best way to go? Are there alternatives?

Any help would be greatly appreciated!

Many thanks,

  -- Stan