Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: How to access the name of an element of a list?

Tags:

r

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

like image 428
SpaceGr4vy Avatar asked Oct 25 '25 22:10

SpaceGr4vy


1 Answers

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).

like image 161
CL. Avatar answered Oct 27 '25 10:10

CL.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!