Last active
April 1, 2016 16:55
-
-
Save etiennebr/9eff944afee39b8a88e3243cc6def66d to your computer and use it in GitHub Desktop.
R - Pack multiple files in a zip
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' Pack multiple files in a zip | |
#' | |
#' @export | |
#' @param fz Complete zip filename and path | |
#' @param fs Named List. Names are files names and content to be passed to FUN | |
#' @param FUN Function for writing to disc (defautl write.csv). Has to accept content as | |
#' first argument and file name as second. Other arguments are passed using ... | |
#' @param temp.dir Temporary directory to write files and zip. Is appened to file names | |
#' if not NULL. | |
#' @param flags A character string of flags to be passed to the command. Defaults is \code{-r9Xj} | |
#' See more at \link{zip{utils}} and \url{http://www.info-zip.org/mans/zip.html}. | |
#' @param ... other arguments passded to FUN | |
#' @details If you receive a status 127 it might be due to the path to zip.exe being undefined | |
#' you can set it using Sys.setenv(R_ZIPCMD="/usr/bin/zip") or | |
#' Sys.setenv(R_ZIPCMD="c:/rtools/bin/zip.exe") on windows. You can also set it permanently | |
#' system-wide by adding the directory to the path. | |
zipack <- function(fz, fs, FUN=write.csv, temp.dir=dirname(fz), flags="-r9Xj", ...) { | |
if(!file.exists(temp.dir)) dir.create(temp.dir) | |
if(!is.null(temp.dir)) names(fs) <- file.path(temp.dir, names(fs)) | |
# write files to temp dir | |
lapply(1:length(fs), function(i) FUN(fs[[i]], file=names(fs[i]), ...)) | |
# compress | |
res <- zip(zipfile=fz, files=names(fs), flags = flags) | |
# cleanup | |
lapply(names(fs), unlink) | |
# return path | |
attr(fz, "contentType") = "application/zip" | |
return(invisible(fz)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment