R: Export and import a list to .txt file
Asked Answered
R

3

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?

Rea answered 10/12, 2014 at 23:29 Comment(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.Middleoftheroad
why not use ?saveRDS or something?Brooder
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()-edCyanine
@Middleoftheroad 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.Rea
S
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.

Sleepwalk answered 11/12, 2014 at 0:8 Comment(2)
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.Chemush
And how would you import the list back in from the .txt?Antofagasta
C
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
Chemush answered 28/2, 2017 at 7:20 Comment(0)
T
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
Trespass answered 22/1, 2020 at 9:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.