Clyde Frog
Clyde Frog

Reputation: 483

Listing named dataframes

Let two dataframes be built by

df1<-data.frame(1,2)
df2<-data.frame(3,4)

and listed by

list<-list(df1,df2)

Then, the dataframes' names are not getting imported into the list. Yet, their names appear if the code is changed to

list<-list(df1=df1,df2=df2)

However, as I build lists consisting of hundreds of dataframes (imported from Quandl) this means a lot of additional typing. Is there a more elegant solution?

Upvotes: 1

Views: 76

Answers (2)

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59970

mget finds the objects given as a character vector in it's first argument and returns a named list. You can either supply a character vector of the object names you want, or use ls() to use a regular expression to select the objects you want from the Global Environment (by default, you can specify other environments for mget to look for objects in):

mget(c("df1","df2"))
#$df1
#  X1 X2
#1  1  2

#$df2
#  X3 X4
#1  3  4

The use of a regular expression seems well suited to your case where you have hundreds of data.frames...

mget( ls( pattern = "df[0-9]+" ) )
#$df1
#  X1 X2
#1  1  2

#$df2
#  X3 X4
#1  3  4

Upvotes: 2

Rich Scriven
Rich Scriven

Reputation: 99331

Here's a way that works well on long lists.

> q <- quote(list(df1, df2))
> setNames(eval(q), as.character(q[-1]))
# $df1
#   X1 X2
# 1  1  2
#
# $df2
#   X3 X4
# 1  3  4

q is an unevaluated expression. When we call eval on it, it gets evaluated and we can turn the expression into a character vector to get the names. setNames is nice for applying names to a list, as it returns the named list as the result.

> q
# list(df1, df2)
> as.character(q)
# [1] "list" "df1"  "df2" 

Upvotes: 0

Related Questions