1

I need to create a loop for converting several list into dataframe, and then write each dataframe as csv. I mean, I want to (i) run a loop for unlist all my lists + convert them into data.frames, and (ii) write each list as CSV.

I ran the following scrip which works for one of my lists but I need to do the same for many of them.

Script to convert a nested list (e.g., list1) in data frame, and write as CSV

data <- as.data.frame(t(do.call(rbind,unlist(list1,recursive = FALSE))))
write.csv(data,"list1.csv"))

Please note that "list1" is one of my list that I wrote as an example. I created an script (done <- ls(pattern="list")) to get a vector with the name of all my lists load in the R environment. So that, I should apply the step (i) and (ii) to all the names in the "done" vector. Was it clearer now?

I would really appreciate if you can help me to create the loop?

Juani
  • 11
  • 1
  • Have you tried `data.frame(list1)`? In R, data.frame is just a bunch of list printed together vertically one by one. This syntax even works on nested lists, assuming each of the sublist is a column of your intended data.frame. – Vlo Sep 28 '16 at 15:38
  • I already know how to retrieve each dataframe from each list (please, see provided scripts above) but the problem is that I have a looooot of lists, and I would like to run the same script to all of them. So that I need a loop. – Juani Sep 28 '16 at 15:51
  • A similar question/answer [here](http://stackoverflow.com/questions/26707724/writing-multiple-data-frames-into-csv-files-using-r). – aosmith Sep 28 '16 at 15:57

2 Answers2

0
for(i in 1:nrow(done){
       list_name <- done[i]
       data <- as.data.frame(t(do.call(rbind,unlist(noquote(list_name),recursive = FALSE))))
       write.csv(data,paste0(list_name,".csv"))
}
liamvt
  • 203
  • 1
  • 9
  • I think that it is almost there but I got the following error: Error in do.call(rbind, unlist(noquote(list_name), recursive = FALSE)) : second argument must be a list – Juani Sep 28 '16 at 16:00
0
fun <- function(x){
  data <- as.data.frame(t(do.call(rbind,unlist(paste0("list",x),recursive = FALSE))))
  write.csv(data,paste0("list",x,".csv"))
}

fun(1:n)

I believe this is the most efficient way.

Stephen
  • 324
  • 2
  • 9