0

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?

HNSKD
  • 1,614
  • 2
  • 14
  • 25
  • Have you tried `list2env(mylst, .GlobalEnv)`? – lukeA Oct 14 '16 at 07:58
  • @lukeA I tried `list2env(l1, .GlobalEnv)`. It gives `Error in list2env(l1, .GlobalEnv) : names(x) must be a character vector of the same length as x` – HNSKD Oct 14 '16 at 08:03
  • Is the answer here, http://stackoverflow.com/questions/12215032/use-loop-to-split-a-list-into-multiple-dataframes ? See @ptocquin 's answer, I think it's what you want. – DarrenRhodes Oct 14 '16 at 08:06
  • Maybe put an `eval(as.symbol())` around `list` in the loop? – Acarbalacar Oct 14 '16 at 08:10
  • 1
    I believe the error comes from the list elements having no names. I did not see that. If you set the names, it will work. – lukeA Oct 14 '16 at 08:12

2 Answers2

2

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)
  }
}
shadow
  • 21,823
  • 4
  • 63
  • 77
1

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)
lukeA
  • 53,097
  • 5
  • 97
  • 100