如何在R中将列表另存为文件以便在Python中读取?

时间:2019-06-20 07:37:36

标签: r list

我有一个用R生成的列表。我想将其保存为一个外部文件,然后,我想用Python读取此文件。

我用过:

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

但是我收到此错误消息:

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

编辑:

这是我的列表的结构(我只显示一部分):

$`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"

有帮助吗?

2 个答案:

答案 0 :(得分:1)

尝试以附加文本模式打开连接,open = "at",然后使用lapply函数writeLines一次写入一个向量。

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

上面的代码将垂直矢量,一个接一个地写。要逐行写文本,请使用以下代码:

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

字段分隔符collapse可以是任何其他字符,例如制表符"\t"或逗号。

答案 1 :(得分:0)

这几乎就是JSON的用途。在R(其中l是列表)中执行以下操作:

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

然后在Python中执行此操作:

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