4

I have a list of dataframes with results from some time series forecasting, each dataframe has a name:

list.of.results <- list(modelA, modelB, modelC)

Now, I am looping through the list and performing some tests on the results of each model, however I need to extract the name of the dataframe as a string that I am currently looping through.

This gets me a null:

names(list.of.results)
> NULL

Any ideas how to do that? Thanks

SpaceGr4vy
  • 105
  • 1
  • 7

3 Answers3

3

Rephrasing the question, the goal is to create a list where the list elements have names according to the objects that have been assigned to them. If a is assigned to the first list element, the first name should automatically become a.

This can be achieved by using makeNamedList instead of list. The function makeNamedList is a condensed result from this question.

makeNamedList <- function(...) {
  structure(list(...), names = as.list(substitute(list(...)))[-1L])
}

Example:

mylist <- makeNamedList(cars, iris)
str(mylist)

# List of 2
# $ cars:'data.frame':  50 obs. of  2 variables:
#   ..$ speed: num [1:50] 4 4 7 7 8 9 10 10 10 11 ...
# ..$ dist : num [1:50] 2 10 4 22 16 10 18 26 34 17 ...
# $ iris:'data.frame':  150 obs. of  5 variables:
#   ..$ Sepal.Length: num [1:150] 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
# ..$ Sepal.Width : num [1:150] 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
# ..$ Petal.Length: num [1:150] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
# ..$ Petal.Width : num [1:150] 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
# ..$ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

So makeNamedList(cars, iris) is equivalent to list(cars = cars, iris = iris).

Community
  • 1
  • 1
CL.
  • 14,577
  • 5
  • 46
  • 73
2

you have to assign the names when creating the list

first assign the names after creating the list

names(list.of.results) <- c("modelA","modelB","modelC")

EDIT: You can search all the models in your environment and assign the names like this

names(list.of.results) <- ls(pattern = "model")

then you can call the name like

names(list.of.results)[1]
GGA
  • 385
  • 5
  • 22
  • 1
    Yes, that is one way around it, thanks. However, there must be a better way than this. The models already have names, plus I have many more than 3 models, so I would like to avoid typing it by hand into the vector. – SpaceGr4vy Feb 13 '16 at 12:27
1

mget is an option:

x <- 1
y <- 2
mget(c("x", "y"))
#$x
#[1] 1
#
#$y
#[1] 2

However, the best solution would be to put the objects into the list when they are created.

Roland
  • 127,288
  • 10
  • 191
  • 288