4

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?

Community
  • 1
  • 1
Remi.b
  • 17,389
  • 28
  • 87
  • 168
  • 4
    `dput` `dump` or `save` will all write out R objects to an external file. `save` will give a binary format while the other two text representations. – thelatemail Dec 10 '14 at 23:35
  • 1
    why not use `?saveRDS` or something? – rawr Dec 10 '14 at 23:36
  • 1
    If you wanted exactly what you see on console output, then: `cat(capture.output(print(my.list), file="test.txt")` although I think the dput strategy will be superior since it can be `source()`-ed – IRTFM Dec 10 '14 at 23:45
  • 1
    @thelatemail I didn't know these functions and they were exactly what I needed. I ended up using `dput` and `dget`. Can you convert your comment into an answer? Thanks. – Remi.b Dec 11 '14 at 17:54

3 Answers3

0

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.

Michele Usuelli
  • 1,970
  • 13
  • 15
  • This won't work reliably: list names can have . `.` in them, and so you can't guarantee that re-building the structure will result in the same list. In fact, I think they can have basically any character in them, e.g. `list('a:2^ 3' = 42)` works. – naught101 Feb 28 '17 at 07:12
  • And how would you import the list back in from the .txt? – Sebastian Hesse Apr 17 '19 at 16:16
0

You could just use the yaml library:

R> library(yaml)
R> l1 <- list('1'=2, se7en=list('som:eth|ng~horr1ßl€'=42))
R> l1
$`1`
[1] 2

$se7en
$se7en$`som:eth|ng~horr1ßl€`
[1] 42
R> cat(as.yaml(l1), file='blah.txt')
R> l2 <- yaml.load_file('blah.txt')
R> l2
$`1`
[1] 2

$se7en
$se7en$`som:eth|ng~horr1ßl€`
[1] 42
naught101
  • 18,687
  • 19
  • 90
  • 138
0

I export lists into YAML format with CPAN YAML package

l <- list(a="1", b=1, c=list(a="1", b=1))
yaml::write_yaml(l, "list.yaml")

Bonus of YAML that it's a human readable text format so it's easy to read or share

$ cat list.yaml
a: '1'
b: 1.0
c:
  a: '1'
  b: 1.0