0

Say I have the following:

df1 <- data.frame()
df2 <- data.frame()
mylist = list(df1, df2)

Is there a function that will return me the names of these two data frames, i.e. returns me 'df1' 'df2'? I know that names(mylist) will just return me NULL.

zx8754
  • 42,109
  • 10
  • 93
  • 154
  • 1
    Try to name your dfs in the list `mylist = list(df1 = df1, df2 = df1)`, then simple `names(mylist)` would give you the names. – zx8754 Jul 06 '17 at 09:29
  • What about if the data frames in my list have really long names, and so it doesn't look very tidy to repeat the name? – bigbadbrad Jul 06 '17 at 11:23
  • How did you get those dfs to your workspace? I rarely manually create lists of dataframes with names as you have shown in the example, usually they are created while reading/processing data within lapply. – zx8754 Jul 06 '17 at 11:27
  • [This post](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) is pretty darn similar. See gregor's answer there for tips on working with lists of data.frames. My answer there is close to akrun's below and uses a regular expression for pattern matching. – lmo Jul 06 '17 at 16:27

2 Answers2

0

If we create the list with mget, we can get the names

lst1 <- mget(paste0("df", 1:2))
names(lst1)
#[1] "df1" "df2"
akrun
  • 674,427
  • 24
  • 381
  • 486
  • NOTE: this can also work for many datasets. Suppose if there are 100 data objects like 'df1', 'df2', ...., 'df100', if time and energy persists, one can do `list(df1 = df1, df2 = df2, ....df100 = df100)` – akrun Jul 06 '17 at 10:09
0
mylist <- list()
mylist[["df1"]] <-df1
mylist[["df2"]] <-df2
names(mylist)

or

mylist[[deparse(substitute(df1))]] <-df1
Shen
  • 157
  • 1
  • 10