如何在R中将列表输出到文件

11
假设有一本书的列表及其作者,将数据读入一个名为“LS”的列表后,我试图将其输入文件中,但输出结果为:
> write.table(LS, "output.txt")
Error in data.frame(..., title = NULL,  : 
  arguments imply differing number of rows: 1, 0

> write(LS, "output.txt")
Error in cat(list(...), file, sep, fill, labels, append) : 
  argument 1 (type 'list') cannot be handled by 'cat'

我能够使用dput,但我希望数据格式良好(文件中不重复出现关键字)。有什么建议吗? 谢谢

更新 dput(head(LS, 2))

list(structure(list( title = "Book 1", 
authors = list(structure(c("Pooja", "Garg"),
 .Names = c("forename","surname")), 
structure(c("Renu", "Rastogi"), 
.Names = c("forename","surname")))),
 .Names = c("title", "authors")), 

structure(list( title = "Book 2", 
 authors = list(structure(c("Barry", "Smit"), .Names = c("forename", 
    "surname")), structure(c("Tom", "Johnston"), .Names = c("forename", 
    "surname")))), .Names = c("title", "authors")))

1
我认为您需要评论一下为什么您认为dput的输出不可接受。您期望/希望得到什么样的输出? - Dason
@Dason 在dput中,关键词“book”和“authors”将在整个文件中重复出现,而我希望它们只出现在头部作为csv文件。 - Thomas Lee
放置一些示例数据将有所帮助(在问题中包含 dput(head(LS,2)),这样我们就可以看到数据的结构。 - mnel
你为什么要写入文件?如果只是为了让 R 以后读取,可以使用 save - Aaron left Stack Overflow
@Aaron 我想以后用Java读取数据,所以我不知道那样行不行。 - Thomas Lee
感谢您的跟进,Thomas。如果数据框方法对您有用,请单击旁边的复选标记,以便其他人知道您的问题已解决。您还可以单击任何问题(包括已选中的问题)旁边的向上箭头,表示答案很有用,无论您最终使用的是否为解决方案。 - Aaron left Stack Overflow
4个回答

10

你可以首先将列表转换为数据框:

LS.df = as.data.frame(do.call(rbind, LS))

或者

LS.df = as.data.frame(do.call(cbind, LS))

那么你可以简单地使用write.csv或write.table保存LS.df


9

通过您提供的数据和 rjson 库进行操作。

library(rjson)

# write them to a file
cat(toJSON(LS), file = 'LS.json')


LS2 <- fromJSON('LS.json')


# some rearranging to get authors back to being a data.frame

LS3 <- lapply(LS2, function(x) { x[['authors']] <-  lapply(x[['authors']], unlist); x})

identical(LS, LS3)

## TRUE

文件看起来像这样:
[{"title":"Book 1","authors":[{"forename":"Pooja","surname":"Garg"},{"forename":"Renu","surname":"Rastogi"}]},{"title":"Book 2","authors":[{"forename":"Barry","surname":"Smit"},{"forename":"Tom","surname":"Johnston"}]}]

如果你想让每本书单独一行,则可以使用:

.json <-  lapply(LS, toJSON)
# add new lines and braces

.json2 <- paste0('[\n', paste0(.json, collapse = ', \n'), '\n]')
 cat(.json)
[
{"title":"Book 1","authors":[{"forename":"Pooja","surname":"Garg"},{"forename":"Renu","surname":"Rastogi"}]}, 
{"title":"Book 2","authors":[{"forename":"Barry","surname":"Smit"},{"forename":"Tom","surname":"Johnston"}]}
]

谢谢您的解决方案,但数据框对我来说更容易。 - Thomas Lee

2
我使用RJSONIO包。
library(RJSONIO)

exportJSON <- toJSON(LS)
write(exportJSON,"LS.json")

0

最好使用format()函数

LS.str <- format(LS)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接