Search code examples
rlistmodelglmnamed

Storing an object to a list and giving it a name stored in a character vector in R


I am running glm classifiers and I want to store the models in a named list giving to each model the name of the predictor used in the classifier -- extracted from a character vector. But I am getting an error.

For a reproducible example I use the mtcars dataset (base R):

> data(mtcars)
> results <- list()
> model1 <- glm(am ~ hp, mtcars, family ="binomial")
> results <- list()
> names <- c("hp"  , "cyl")
> results <- append(results, list(names[1] = model1))
Error: unexpected '=' in "results <- append(results, list(names[1] ="

Your advice will be appreciated.


Solution

  • Replace your last line with

    results[[names[1]]] <- model1