There's nothing built in that would do anything like this. You could create a function that could help. Maybe something like this
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)
}
Here I create a list of savers
that look at the different object types and write them out to disc. Then with a sample list
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)
I can write them out with
save_list(x)
Note that you really need a named list in order to determine file names later. Here I explicitly name the elements of x
but if they are not present, simple indexing will be used. You can also swap out the saving functions to see what would be written by just printing the value to screen.
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)"
Note that this does assume the directory already exists. If you need to check first, see this question for possible solutions.