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 但我希望数据的格式正确(文件中没有重复关键字的冗余)。有什么建议么?谢谢

更新 输入(头(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")))
4

4 回答 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

于 2012-10-04T00:27:12.103 回答
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"}]}
]
于 2012-10-04T00:29:45.277 回答
2

我使用 RJSONIO 包。

library(RJSONIO)

exportJSON <- toJSON(LS)
write(exportJSON,"LS.json")
于 2015-02-16T04:07:31.747 回答
0

最好使用 format()

LS.str <- format(LS)

于 2016-04-18T23:20:03.003 回答