0

let's say I have these many dataset (let's imagine 1000 datasets) :

df1 = data.frame(x = 1:10)

df2 = data.frame(x = 2:11)

df3 = data.frame(x = 3:5)

df4 = data.frame(x = 11:20)

I want to create a list that is called L as follows

L = list(df1,df2,df3,df4)

but if I have thousands of dataframes, it would be difficult to write each dataframe namein the list. Would take forever. Would like a function that can make creating this list easier. Thanks.

Anas116
  • 797
  • 2
  • 9
  • 1
    Do the names of your data frames have a pattern? Did they name sequantially like df1, df2, df3 so on? – maydin Nov 18 '22 at 16:14
  • yes that's correct – Anas116 Nov 18 '22 at 16:14
  • 1
    `L = lapply(1:4, function(x) {get(paste0("df",x)) })` where 4 is the maximum number at the end of your dataframes. – maydin Nov 18 '22 at 16:18
  • Thanks a lot. Can you add your answer to the answer section so everyone can see the answer. Thanks again – Anas116 Nov 18 '22 at 16:19
  • How did you create those in the first place? It's better not to have a bunch of variables with indexes in their names. Think would be much easier if you created those related tables in a list to start with. While you can technically use `get()` or `mget()`, it's really a bad code smell in R. – MrFlick Nov 18 '22 at 16:21

2 Answers2

2

By using BaseR,

n = 4
L = lapply(1:n, function(x) {get(paste0("df",x)) })

where n is the maximum number at the end of your dataframe names.

maydin
  • 3,715
  • 3
  • 10
  • 27
2

You can use get() to extract data frames from their object name.


N <- 4
nms <- sprintf("df%i",1:N)
out <- list()
for(i in 1:N){
out[[i]] <- get(nms[i])  
}

out
Brian Davis
  • 990
  • 5
  • 11