2

I have three data frames: df1, df2, df3.

I want to merge them into a list:

dataframes <- list(df1, df2, df3)

How can I use the names of each data frame for their corresponding list element names?

So that instead of this:

> names(dataframes)
[1] "" "" ""

I get this:

> names(dataframes)
[1] "df1" "df2" "df3"
0

2 Answers 2

1

You need to name them when creating the list:

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

names(dataframes)
#"df1" "df2" "df3"
Sign up to request clarification or add additional context in comments.

Comments

0

Here is one option using a loop. I assume that df1, df2, and df3 are data frames, and have been defined somewhere.

i <- 1
lst <- list()   # an empty list

while (i <= 3) {
    df_name <- paste0("df", i)
    lst[[i]] <- get(df_name)
    names(lst)[i] <- df_name
    i <- i + 1
}

names(lst)

[1] "df1" "df2" "df3"

Demo

While many view using loops in R as being evil, the above case is not so bad, because we simply add new list items (and their names) one by one, as the loop progresses.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.