R: Print list to a text file

前端 未结 8 1789
执念已碎
执念已碎 2020-11-30 21:17

I have in R a list like this:

> print(head(mylist,2))
[[1]]
[1] 234984  10354  41175 932711 426928

[[2]]
[1] 1693237   13462

Each eleme

相关标签:
8条回答
  • 2020-11-30 21:49

    I saw in the comments for Nico's answer that some people were running into issues with saving lists that had lists within them. I also ran into this problem with some of my work and was hoping that someone found a better answer than what I found however no one responded to their issue.

    So: @ali, @FMKerckhof, and @Kerry the only way that I found to save a nested list is to use sink() like user6585653 suggested (I tried to up vote his answer but could not). It is not the best way to do it since you link the text file which means it can be easily over written or other results may be saved within that file if you do not cancel the sink. See below for the code.

    sink("mylist.txt")
    print(mylist)
    sink()
    

    Make sure to have the sink() at the end your code so that you cancel the sink.

    0 讨论(0)
  • 2020-11-30 22:01

    depending on your tastes, an alternative to nico's answer:

    d<-lapply(mylist, write, file=" ... ", append=T);
    
    0 讨论(0)
  • 2020-11-30 22:02

    Here is another

    cat(sapply(mylist, toString), file, sep="\n")
    
    0 讨论(0)
  • 2020-11-30 22:03

    Here's another way using sink:

    sink(sink_dir_and_file_name); print(yourList); sink()

    0 讨论(0)
  • 2020-11-30 22:05

    Another way

    writeLines(unlist(lapply(mylist, paste, collapse=" ")))
    
    0 讨论(0)
  • 2020-11-30 22:07

    Format won't be completely the same, but it does write the data to a text file, and R will be able to reread it using dget when you want to retrieve it again as a list.

    dput(mylist, "mylist.txt")
    
    0 讨论(0)
提交回复
热议问题