1

I have a list of dataframes such as follows:

x <- c(1, 2, 3, 4, 5)
y <- c(5, 4, 3, 2, 1)
df1 <- data.frame(x)
df2 <- data.frame(y)
x <- list(df1, df2)

I want to print the names of the dataframes in list x with a for loop such as this:

for (i in x) {
  deparse(substitute(x[i]))
}

But it doesn't work. My goal is to have the names of the dataframes printed out as characters such as this:

[1] df1
[2] df2

Thanks!

Marco Pastor Mayo
  • 803
  • 11
  • 25

2 Answers2

5

Data.frames don't have "names". A variable can point to a data.frame, but a data.frame can exist without a name at all (like if you did x <- list(data.frame(x), data.frame(y))). So your data.frame isn't named df1; df1 is a variable name that happens to point to a data.frame.

If you put a variable in a list, the value of the variable is placed in the list, not the variable name itself. So if you want to keep a name of the variable that originally held the object in the list, you'd need to store the name in the list. One common way to do that is

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

Then you can set the names with names(x). If you want to see other ways to create lists that keep the object names, see the existing question: Can lists be created that name themselves based on input object names?

MrFlick
  • 195,160
  • 17
  • 277
  • 295
0

There were some very helpful point: using x <- list(df1=df1, df2=df2) to save the names of the data frames in the list and using the names() function. Here is the code I used to definitively print the names of the data frames in the list:

x <- c(1, 2, 3, 4, 5)
y <- c(5, 4, 3, 2, 1)
df <- data.frame(x, y)
df1 <- data.frame(x)
df2 <- data.frame(y)
x <- list(df1=df1, df2=df2)
for (i in 1:2) {
print(as.character(names(x)[i]))
}

And this prints out the names of the data frames on the list.

Marco Pastor Mayo
  • 803
  • 11
  • 25