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

Tho*_*Lee 11 r list

假设有一个包含作者的书籍列表,在将数据读入列表"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'
Run Code Online (Sandbox Code Playgroud)

我能够使用dput,但我希望数据格式良好(整个文件没有重复关键字的冗余).有什么建议?谢谢

UPDATE 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")))
Run Code Online (Sandbox Code Playgroud)

Ali*_*Ali 10

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

LS.df = as.data.frame(do.call(rbind, LS))
Run Code Online (Sandbox Code Playgroud)

要么

LS.df = as.data.frame(do.call(cbind, LS))
Run Code Online (Sandbox Code Playgroud)

然后你可以用write.csv或write.table简单地保存LS.df


mne*_*nel 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
Run Code Online (Sandbox Code Playgroud)

该文件看起来像

[{"title":"Book 1","authors":[{"forename":"Pooja","surname":"Garg"},{"forename":"Renu","surname":"Rastogi"}]},{"title":"Book 2","authors":[{"forename":"Barry","surname":"Smit"},{"forename":"Tom","surname":"Johnston"}]}]
Run Code Online (Sandbox Code Playgroud)

如果您希望每本书都在一个单独的行上,那么您可以使用

.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"}]}
]
Run Code Online (Sandbox Code Playgroud)