R: Export and import a list to .txt file

10,594

You can save your list using these commands (given that there are no element names containing a dot)

l1 <- list(a = 1, b = list(c = 1, d = 2))
vectorElements <- unlist(l1)
vectorPaths <- names(vectorElements)
vectorRows <- paste(vectorPaths, vectorElements)
write.table(vectorRows, "vectorRows.txt", row.names = FALSE, col.names = FALSE, quote = FALSE)

Each line of the file corresponds to an element in this format

node1.node2.node3 leaf

Then, you'll be able to re-build the list structure.

Share:
10,594
Remi.b
Author by

Remi.b

Updated on June 30, 2022

Comments

  • Remi.b
    Remi.b almost 2 years

    This post suggests a way to write a list to a file.

    lapply(mylist, write, "test.txt", append=TRUE, ncolumns=1000)
    

    The issue with this technic is that part of the information of the list (the structure into subparts and the names of the subparts) disappear and it is therefore very complicated (or impossible if we lost the extra information) to recreate the original list from the file.

    What is the best solution to export and import (without causing any modification, including the names) a list?