【问题标题】:Exporting List Structure to Folder Structure将列表结构导出到文件夹结构
【发布时间】:2017-08-12 05:47:42
【问题描述】:

我有一个列表“list_export”,其中包含两个子列表“list_plots”和“list_tables”,分别包含 ggplots 和数据框。

list_plots <- list(plot1, plot2, plot3)
list_tables <- list(table1, table2, table3)
list_export <- list(list_plots, list_tables)

我想将列表的树形结构导出到具有正确数据类型的文件夹结构中,例如:

list_export/list_plots/plots[1-3].png
list_export/list_tables/tables[1-3].csv

有没有办法将列表的结构直接导出到文件夹?它希望将解决方案应用于 n 级,而不仅仅是 2。

【问题讨论】:

    标签: r export directory nested-lists


    【解决方案1】:

    没有内置的东西可以做这样的事情。您可以创建一个可以提供帮助的函数。也许是这样的

    savers <- list(
        "ggplot" = function(pp, base) ggsave(filename=paste0(base,".png"), plot=pp),
        "data.frame" = function(dd, base) write.table(dd, file=paste0(base,".txt"))
    )
    
    save_list <- function(x, prefix=deparse(substitute(x)), savers=savers) {
      ids = as.character(if(!is.null(names(x))) {names(x)} else {seq_along(x)})
      ids[nchar(ids)<1] <- as.character(seq_along(x)[nchar(ids)<1])
      ret <- Map(function(x, id) {
         found <- FALSE
         for(type in names(savers)) {
           if(inherits(x, type)) {
               found <- TRUE
               ret <- savers[[type]](x, file.path(prefix, id))
               return(ret)
           }
         }
         if (!found) {
           if (class(x)=="list") {
              save_list(x, file.path(prefix, id), savers=savers)
           } else {
              stop(paste("unable to save object of type:", class(x)))
           }
         }
      }, x, ids)
      invisible(ret)
    }
    

    在这里,我创建了一个savers 列表,查看不同的对象类型并将它们写入磁盘。然后是一个示例列表

    plot_list <- Map(function(x) ggplot(mtcars) + geom_point(aes(cyl, disp)) + ggtitle(x), paste("plot", 1:3))
    data_list <- replicate(4, data.frame(x=runif(10), y=rnorm(10)), simplify=FALSE)
    x <- list(plot_list=plot_list, data_list=data_list)
    

    我可以用

    写出来
    save_list(x)
    

    请注意,您确实需要一个命名列表以便稍后确定文件名。这里我明确命名x 的元素,但如果它们不存在,将使用简单的索引。您还可以通过将值打印到屏幕来交换保存功能以查看将写入的内容。

    noop <- list(
        "ggplot" = function(pp, fn) print(paste(paste0(fn,".png"),"(plot)")),
        "data.frame" = function(dd, fn) print(paste(paste0(fn,".txt"), "(df)"))
    )
    save_list(x, savers=noop)
    # [1] "x/plot_list/plot 1.png (plot)"
    # [1] "x/plot_list/plot 2.png (plot)"
    # [1] "x/plot_list/plot 3.png (plot)"
    # [1] "x/data_list/1.txt (df)"
    # [1] "x/data_list/2.txt (df)"
    # [1] "x/data_list/3.txt (df)"
    # [1] "x/data_list/4.txt (df)"
    

    请注意,这确实假定目录已经存在。如果您需要先检查,请参阅this question 了解可能的解决方案。

    【讨论】:

    • 谢谢 MrFlick!
    猜你喜欢
    • 1970-01-01
    • 2020-11-04
    • 2012-06-02
    • 2022-12-12
    • 2012-09-06
    • 2019-07-21
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    相关资源
    最近更新 更多