57

I understand that we cannot export a table if one of its elements is a list. I got a list in R and I want to export it into a CSV or TXT file. Here is the error message that I get when I execute this write.table command :

write.table(mylist,"test.txt",sep=";")

Error in .External2(C_writetable, x, file, nrow(x), p, rnames, sep, eol,  : 
unimplemented type 'list' in 'EncodeElement'

Here is the first element of my list :

$f10010_1
$f10010_1$mots
 [1] X16               ESPRESSO          TDISC             TASSIMO          
 [5] CARTE             NOIRE             A                 LAVAZZA          
 [9] MALONGO           MIO               MODO              123              
[13] CAPSULES          DOSES             78G               LONG             
[17] SPRESSO           CAFE              120G              CLASSIC          
[21] 104G              128G              AROMATIQUE        INTENSE          
[25] 112G              156G              520G              5X16             
[29] PROMO             TRIPACK           X24               126G             
[33] 16                4X16              APPASSIONATAMENTE APPASSIONATEMENTE
[37] BRESIL            CAPSUL            COLOMBIE          CORSE            
[41] CREMOSAMENTE      DELICATI          DELIZIOSAMENTE    DIVINAMENTE      
[45] DOLCEMENTE        EQI               GRAND             GRANDE           
[49] GT                GUATEMALA         HAITI             INTENSAMENTE     
[53] ITALIAN           MAGICAMENTE       MERE              MOKA78G          
[57] PETITS            PRODUCT           PURSMATIN         RESERVE          
[61] RISTRETO          SOAVEMENTE        STYLE             X36              
64 Levels: 104G 112G 120G 123 126G 128G 156G 16 4X16 520G 5X16 78G ... X36

$f10010_1$nblabel
 [1] 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32
[27] 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32
[53] 32 32 32 32 32 32 32 32 32 32 32 32
Levels: 32

$f10010_1$Freq
 [1] 18 16 16 15 14 14  9  9  9  9  9  8  8  8  7  7  7  6  5  5  3  3  3  3  2  2
[27]  2  2  2  2  2  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1
[53]  1  1  1  1  1  1  1  1  1  1  1  1

$f10010_1$pct
 [1] 0.56250 0.50000 0.50000 0.46875 0.43750 0.43750 0.28125 0.28125 0.28125
[10] 0.28125 0.28125 0.25000 0.25000 0.25000 0.21875 0.21875 0.21875 0.18750
[19] 0.15625 0.15625 0.09375 0.09375 0.09375 0.09375 0.06250 0.06250 0.06250
[28] 0.06250 0.06250 0.06250 0.06250 0.03125 0.03125 0.03125 0.03125 0.03125
[37] 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125
[46] 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125
[55] 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125
[64] 0.03125
1

8 Answers 8

Reset to default

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

48

I think the most straightforward way to do this is using capture.output, thus;

capture.output(summary(mylist), file = "My New File.txt")

Easy!

4
  • 3
    the complete file is not captured if the file is large
    – d2a2d
    Apr 2, 2018 at 17:55
  • 1
    @d2a2d - how large is too large? I haven't run into any problems using this method, but if there are limits, then it would be good to know what they are.
    – EcologyTom
    Apr 2, 2018 at 18:02
  • 3
    10000 rows is the limit. Maybe there is a way to change this
    – d2a2d
    Apr 4, 2018 at 17:37
  • 1
    From a cursory look at the ? files I can't see anything in either capture.output or the global options for expanding the limits. If someone else finds anything it would be good to know. Hopefully the method will still be useful for some people.
    – EcologyTom
    Apr 5, 2018 at 10:19
28

So essentially you have a list of lists, with mylist being the name of the main list and the first element being $f10010_1 which is printed out (and which contains 4 more lists).

I think the easiest way to do this is to use lapply with the addition of dataframe (assuming that each list inside each element of the main list (like the lists in $f10010_1) has the same length):

lapply(mylist, function(x) write.table( data.frame(x), 'test.csv'  , append= T, sep=',' ))

The above will convert $f10010_1 into a dataframe then do the same with every other element and append one below the other in 'test.csv'

You can also type ?write.table on your console to check what other arguments you need to pass when you write the table to a csv file e.g. whether you need row names or column names etc.

1
  • One downside to this is the list names aren't retained (i.e. f10010_1$mots)
    – KNN
    Dec 16, 2021 at 15:21
7

using sink function :

sink("output.txt")
print(mylist)
sink()
1
  • 2
    If the list contains tbls larger than 10 rows, rows 11+ of each will be lost: # ... with 263 more rows
    – dez93_2000
    Mar 8, 2019 at 2:20
5

cat(capture.output(print(my.list), file="test.txt"))

from R: Export and import a list to .txt file https://stackoverflow.com/users/1855677/42 is the only thing that worked for me. This outputs the list of lists as it is in the text file

1
  • 1
    If the list contains tbls larger than 10 rows, rows 11+ of each will be lost: # ... with 263 more rows
    – dez93_2000
    Mar 8, 2019 at 2:22
3

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/share/import/etc

$ cat list.yaml
a: '1'
b: 1.0
c:
  a: '1'
  b: 1.0
1
  • this is great, as you say, because it combines readability and further usage of the file
    – Tapper
    Sep 12, 2021 at 20:50
2

You can simply wrap your list as a data.frame (data.frame is in fact a special kind of list). Here is an example:

mylist = list() 
mylist[["a"]] = 1:10 
mylist[["b"]] = letters[1:10]
write.table(as.data.frame(mylist),file="mylist.csv", quote=F,sep=",",row.names=F)

or alternatively you can use write.csv (a wrapper around write.table). For the conversion of the list , you can use both as.data.frame(mylist) and data.frame(mylist).

To help in making a reproducible example, you can use functions like dput on your data.

2
  • Thank you so much for your help. Feb 4, 2019 at 3:04
  • 5
    I believe this will only work if all list elements have the same number of rows
    – dez93_2000
    Mar 8, 2019 at 2:17
0

You can write your For loop to individually store dataframes from a list:

allocation = list()

for(i in 1:length(allocation)){
    write.csv(data.frame(allocation[[i]]), file = paste0(path, names(allocation)[i], '.csv'))
}
0

Here is one way to write list to csv or other format file:

Input list:

test <- list(A=data.frame(m=1:3,n=letters[1:3]), B=1:5)

Export the list to a file:

library(data.table)
outputfile <- "test.csv" #output file name
sep <- "," #define the separator (related to format of the output file)
for(nam in names(test)){
  fwrite(list(nam), file=outputfile, sep=sep, append=T) #write names of the list elements
  ele <- test[[nam]]
  if(is.list(ele)) fwrite(ele, file=outputfile, sep=sep, append=T, col.names=T) else fwrite(data.frame(matrix(ele, nrow=1)), file=outputfile, append=T) #write elements of the list
  fwrite(list(NA), file=outputfile, append=T) #add an empty row to separate elements
}

Output looks like (I can't put picture here because of the level restrictions):

A
m,n
1,a
2,b
3,c

B
1,2,3,4,5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.