Automatically add variable names to elements of a list

r, string

Solution

The key to this is to re-make the list function to stick on the names when you don't supply the names as well.

listN <- function(...){
    anonList <- list(...)
    names(anonList) <- as.character(substitute(list(...)))[-1]
    anonList
}

With this, you make `modelList` as follows:

modelList <- listN(mod1, mod2, mod3, mod4, mod5, mod6)

With the names attached:

R> names(modelList)
[1] "mod1" "mod2" "mod3" "mod4" "mod5" "mod6"

A fuller solution is given here, which is robust to the use of a mixture of anonymous and named arguments to `list`.

listN2 <- function(...){
    dots <- list(...)
    inferred <- sapply(substitute(list(...)), function(x) deparse(x)[1])[-1]
    if(is.null(names(inferred))){
        names(dots) <- inferred
    } else {
        names(dots)[names(inferred) == ""] <- inferred[names(inferred) == ""]
    }
    dots
}

Problem

I have a list of models, and to make the code easiser to maintain (so roubst to adding and removing models) I'd like to have a single place where I store them and their names. To do this I have to solve the following naming problem. Upstream, i have generated models in a way that's less efficient than the following (if it was this compressed, i would `assign` them to their own `env`). ``` lmNms <- c( "mod1", "mod2", "mod3", "mod4", "mod5", "mod6") lapply(lmNms, function(N) assign(N, lm(runif(10) ~ rnorm(10)), env = .GlobalEnv)) ``` Downstream, i have collected the mess into a list: ``` modelList <- list(mod1, mod2, mod3, mod4, mod5, mod6) ``` I have an (un-named) lists of variable output, and attach the names as follows: ``` output <- list(1, 2, 3, 4, 5, 6) names(output) <- lmNms ``` I'd like to be able to use the model names from `modelList`: ``` modelList <- list(mod1, mod2, mod3, mod4, mod5, mod6) names(output) <- someFun(modelList) ``` I'm sure there exists `someFun` -- but I cannot figure it out ... can this be done? To be clear, the aim is to do this without using `lmNms` -- i want to get the names either from `modelList`, or have them attach at the point that i build `modelList` (the point is to avoid `list(a = a, b=b ...)` boilerplate.

Original source

Related problems