Paillou
Paillou

Reputation: 839

How to save a list as a file in R in order to read it in Python?

I have a list I have generated in R. I would like to save it as an external file , and then, I want to read this file in Python.

I used :

write.table(list, file="~/test.txt")

But I get this error message :

Error in write.table(list, file = "~/test.txt") :
 Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  : 
  arguments imply differing number of rows: 9312, 628, 317, 27, 244, 894, 540, 280, 739, 866, 239, 2432, 969, 2033, 75, 509, 539, 321, 6637, 24, 116, 2006, 18, 2695, 16, 47, 32, 34, 28, 102, 44, 462, 84, 30, 73, 77, 29, 400, 60, 80, 31, 101, 680, 100, 58, 126, 112, 122, 155, 123, 167, 138, 149, 202, 246, 296, 240, 68, 350, 583, 46, 701, 467, 636, 654, 56, 418, 230, 64, 90, 74, 72, 67, 61, 55, 41, 40, 35, 25, 23, 22, 20, 19, 17

Edit :

THis is the structure of my list (I only show a part) :

$`5`
  [1] "OTU1159"             "OTU1158"             "UniRef90_A0A1B2YRW1"
  [4] "UniRef90_A0A1B2Z315" "UniRef90_A0A1B2Z316" "UniRef90_A0A1Z9FR83"
  [7] "UniRef90_A0A1Z9FRN0" "UniRef90_A0A1Z9FRT6" "UniRef90_A0A1Z9FSZ6"
 [10] "UniRef90_A0A1Z9FTY0" "UniRef90_A0A1Z9FU92" "UniRef90_A0A1Z9FVK9"
 [13] "UniRef90_A0A1Z9FVU0" "UniRef90_A0A1Z9FWD5" "UniRef90_A0A1Z9FYC5"
$`6`
  [1] "OTU4451"             "OTU4536"             "OTU4458"            
  [4] "OTU4430"             "OTU4435"             "OTU2156"            
  [7] "UniRef90_A0A081FUN4" "UniRef90_A0A081FUN8" "UniRef90_A0A0F5AQ41"
 [10] "UniRef90_A0A0R2PEV0" "UniRef90_A0A0R2U5F4" "UniRef90_A0A0R2UTD5"
 [13] "UniRef90_A0A0R2UUB4" "UniRef90_A0A0R2UW29" "UniRef90_A0A0R2UWJ2"
 [16] "UniRef90_A0A0R2UXE1" "UniRef90_A0A0R2UXE3" "UniRef90_A0A0S8BGF5"

Any help?

Upvotes: 3

Views: 1723

Answers (2)

user10191355
user10191355

Reputation:

This is pretty much what JSON is for. Do the following in R, where l is your list:

library(jsonlite)
write_json(l, "test.json")

And then do this in Python:

import json
with open("test.json") as f:
    l = json.load(f)

Upvotes: 5

Rui Barradas
Rui Barradas

Reputation: 76651

Try opening a connection in append text mode, open = "at" and then lapply function writeLines to write one vector at a time.

fl <- file("~/test.txt", open = "at")
lapply(thelist, writeLines, con = fl)
close(fl)

The code above will write the vectors vertically, one after the other. To write them text line by text line, use something along the lines of this:

fl <- file("~/test.txt", open = "at")
lapply(thelist, function(x){
  x <- paste(x, collapse = " ")
  writeLines(x, con = fl, sep = "\n")
})
close(fl)

The field separator collapse character can be any other character, such as a tab "\t" or a comma.

Upvotes: 1

Related Questions