将列表结构导出到文件夹结构

Exporting List Structure to Folder Structure

我有一个列表 '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 级。

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

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 以了解可能的解决方案。