0

I have several dataframes df1 df2 ... df10

How can I pack these dataframes into a vector?

# Not this:
c(df1, df2, df3, ..., df10)

I've tried it with a for loop:

dataframes <- c()
for (i in 1:10)
  dataframes <- c(dataframes, paste("df", i, sep = ""))

But this just gives me the names of the dataframes as characters instead of the objects themselves.

D. Studer
  • 1,711
  • 1
  • 16
  • 35
  • You should not have separate data.frames. Put them into a list when you create them. Anyway, you can fix that mistake with `mget(paste0("df", 1:10))`. – Roland Nov 12 '20 at 12:35

2 Answers2

1

To create a character vector you can use paste0.

paste0('df', 1:10)
#[1] "df1"  "df2"  "df3"  "df4"  "df5"  "df6"  "df7"  "df8"  "df9"  "df10"

To get the actual objects of these names in a list use mget :

list_df <- mget(paste0('df', 1:10))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

A vector isn't the right tool here. For your purpose you need another container-like structure called list. Suppose you have the names of your dataframes stored in a vector called dataframeNames. Otherwise, create it. The function paste0 concatenates vectors without spacing and coerces all objects in the function-call to characters.

dataframeNames <- paste0('df', 1:10)

Now you need to store your dataframes in a list. This can be done via an lapply. This function applies a given function (in our case a function that takes a name of an object in the current environment and grabs it) to every element of a container-like structure (in our case the character-vector of names) and stores everything in a list.

dataframeList <- lapply(dataframeNames, function(nam) get(nam))

To access these dataframes as list-elements, you can call them by their name or by indexing via double-square brackets.

dataframeList[[1]] #returns the first dataframe
dataframeList[[7]] #returns the seventh dataframe
dataframeList$df7 #returns the seventh dataframe too
Jonas
  • 1,760
  • 1
  • 3
  • 12