HNSKD
HNSKD

Reputation: 1644

How do I split a list containing data frames into the individual data frames?

I have 6 lists (l1,l2,l3,l4,l5,l6) in total and in each list, I have 12 dataframes (df1,df2,df3,...,df10,df11,df12). I would like to split all the lists. This is what I have tried.

split_df<-function(list){
for (i in 1:length(list)){
assign(paste0("df",i),list[[i]])}
}

It only works if I use the for loop only. But it doesnt work with the function.

Let's look at the following list, l1:

l1<-list(data.frame(matrix(1:10,nrow=2)),data.frame(matrix(1:4,nrow=2)))
split_df(l1)
df1
Error: object 'df1' not found
df2
Error: object 'df2' not found

But without the function:

for (i in 1:length(l1)){
assign(paste0("df",i),l1[[i]])}

df1
#   X1 X2 X3 X4 X5
# 1  1  3  5  7  9
# 2  2  4  6  8 10
df2
#   X1 X2
# 1  1  3
# 2  2  4

How do I rectify this?

Upvotes: 0

Views: 962

Answers (2)

shadow
shadow

Reputation: 22293

You use assign locally. So inside the function, you create the data.frames df1 and df2. You can assign these to the global environment instead:

split_df<-function(list){
  for (i in 1:length(list)){
    assign(paste0("df",i), list[[i]], envir = .GlobalEnv)
  }
}

Upvotes: 2

lukeA
lukeA

Reputation: 54237

You can do

l1<-list(data.frame(matrix(1:10,nrow=2)),data.frame(matrix(1:4,nrow=2)))
names(l1) <- paste0("df", seq_along(l1))
list2env(l1, .GlobalEnv)

Upvotes: 1

Related Questions