Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save in a file output a list of unequal length elements

Tags:

file

list

r

save

I have a list of 1000 elements each of them are composed by other lists of different lengths (of about 6000 average length). I need to save it into a .csv or preferably .txt file. As it is a very big object, here I show you the problem through a simple example.

Given the following list of list, that consists of 2 lists which in turn consist respectively of 4 and 6 elements, as follow:

[[1]]
[[1]][[1]]
[1] 7 3 5 4 8

[[1]][[2]]
[1] 5 7 8

[[1]][[3]]
[1] 1 5

[[1]][[4]]
[1] 6


[[2]]
[[2]][[1]]
[1] 1 7 3 4 5 9

[[2]][[2]]
[1] 5 9 2 1

[[2]][[3]]
[1] 6 2 4

[[2]][[4]]
[1] 6 1

[[2]][[5]]
[1] 5 9

[[2]][[6]]
[1] 6

I need to save this list of list in a .csv or preferably .txt file in order to maintain the reference of the list numbers, for example where the first two numbers refers to the list order, as follow:

1, 1, 7, 3, 5, 4, 8
1, 2, 5, 7, 8
1, 3, 1, 5                
1, 4, 6

2, 1, 1, 7, 3, 4, 5, 9
2, 2, 5, 9, 2, 1
2, 3, 6, 2, 4
2, 4, 6, 1
2, 5, 5, 9
2, 6, 6

Has anyone idea about how I could do that? Here is the data in reproducible form:

mylist <- list(list(c(7, 3, 5, 4, 8), c(5, 7, 8), c(1, 5), 6), list(c(1, 
7, 3, 4, 5, 9), c(5, 9, 2, 1), c(6, 2, 4), c(6, 1), c(5, 9), 
    6))
like image 391
M.C. Pagliarella Avatar asked Dec 09 '25 14:12

M.C. Pagliarella


2 Answers

Here's an example. (ccat() isn't really necessary, it's just a helper function to save a little bit of typing. If you instead define ccat with file="" this will print to the console instead.)

ccat <- function(...,file="myfile.txt") {
   cat(...,file=file,append=TRUE)                  
}
for (i in seq_along(mylist)) {
    for (j in seq_along(mylist[[i]])) {
        ccat(i,j,mylist[[i]][[j]],sep=", ")
        ccat("\n")
    }
    ccat("\n")
}                                     
like image 117
Ben Bolker Avatar answered Dec 11 '25 11:12

Ben Bolker


Consider writeLines() with nested lapply(). Below writes to file and creates corresponding newlist object to memory:

file <- "/path/to/myfile.txt"
conn <- file(description=file, open="w")

newlist <- lapply(seq_len(length(mylist)), function(i){

  lapply(seq_len(length(mylist[[i]])), function(j) {
      temp <- c(i, j, mylist[[i]][[j]])
      writeLines(text=paste(temp, collapse=","), con=conn, sep="\r\n")  
  })

})
close(conn)
like image 35
Parfait Avatar answered Dec 11 '25 09:12

Parfait



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!