【问题标题】:How to output a list to file in R如何将列表输出到R中的文件
【发布时间】:2012-10-03 23:49:00
【问题描述】:

假设有一个作者的书籍列表,在将数据读入列表“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")))

【问题讨论】:

  • 我认为您需要评论为什么您认为 dput 的输出不可接受。您的预期/期望输出是什么?
  • @Dason 在输入中,关键字“book”和“authors”将在整个文件中重复出现,而我希望它们仅作为 csv 文件出现在标题中。
  • 放置一些示例数据会有所帮助(如何在问题中包含dput(head(LS,2)),以便我们查看数据的结构
  • 为什么要写入文件?如果只是供 R 稍后阅读,请改用save
  • @Aaron 我想稍后使用 Java 读取数据,所以我不知道这是否可行。

标签: r list


【解决方案1】:

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

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

或者

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

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

【讨论】:

    【解决方案2】:

    使用您提供的数据和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"}]}
    ]
    

    【讨论】:

    • 感谢您的解决方案,但数据框对我来说更容易
    【解决方案3】:

    我使用 RJSONIO 包。

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

    【讨论】:

      【解决方案4】:

      最好用format()

      LS.str &lt;- format(LS)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-11
        • 2017-09-29
        • 2018-08-13
        • 1970-01-01
        相关资源
        最近更新 更多