finding names of un-named list elements I have a naming problem: lists with un-named elements.  I wish to get the names of the elements in the list, without going back upstream to where the list was created. An example is modelList below:

## naming problem
lmNms &lt;- c( "mod1", "mod2", "mod3", "mod4", "mod5", "mod6")
lapply(lmNms, 
       function(N) assign(N, lm(runif(10) ~ rnorm(10)), env = .GlobalEnv))
modelList &lt;- list(mod1, mod2, mod3, mod4, mod5, mod6)


I have written the below function which takes the list and the environment as arguments (as well as an argument to return names only), looks for a matching object in the target environment, and then attaches that name to the element and returns the list. 

nameListObjects &lt;- function(LIST, ENV = NULL, NAMES.ONLY = FALSE) {
    if(is.null(ENV)) ENV &lt;- .GlobalEnv
    for(i in seq_along(LIST)){
        # check the class of all objects in the target environment
        classMatches &lt;- sapply(ls(ENV), 
                               function(N) class(get(N)) == class(LIST[[i]]))
        # see which objects of matching class are all.equal to the subject
        TF &lt;- sapply(names(classMatches[classMatches]), 
                 function(N) is.logical(all.equal(LIST[[i]], get(N))))
        names(LIST)[i] &lt;- names(classMatches[classMatches])[TF]
    }
    if(NAMES.ONLY) names(LIST) else LIST
}

R&gt;nameListObjects(modelList, NAMES.ONLY=TRUE)
[1] "mod1" "mod2" "mod3" "mod4" "mod5" "mod6"


This took me to the edge of my R ability. 

I'm interested in better ways to do this (i presume there are multiple better ways), problems with this approach, and any other comments.
You could have used identical to compare objects. However, I would recommend representing all objects by their MD5 digests, so you can then use match to find the matches:

nameListObjects &lt;- function(LIST, ENV = NULL, NAMES.ONLY = FALSE) {

  if(is.null(ENV)) ENV &lt;- .GlobalEnv
  require(digest)
  list.md5   &lt;- sapply(LIST, digest)
  env.names  &lt;- ls(envir = ENV)
  env.md5    &lt;- sapply(env.names, function(x)digest(get(x, envir = ENV)))
  list.names &lt;- env.names[match(list.md5, env.md5)]

  if(NAMES.ONLY) list.names else setNames(LIST, list.names)
}

nameListObjects(modelList, NAMES.ONLY=TRUE)
[1] "mod1" "mod2" "mod3" "mod4" "mod5" "mod6"