R/loading_and_writing.R

Defines functions save_plot saveRDS.gz readRDS.gz

Documented in readRDS.gz save_plot saveRDS.gz

#' Save a ggplot object in multiple output formats
#'
#' @param myplot A ggplot object
#' @param fname An output filename
#' @param w The width of the plot in inches (default: 8)
#' @param h The height of the plot in inches (default: 8)
#' @param dpi The dpi (default: 400)
#' @author Martin Jung
#' @export
save_plot <- function(myplot,fname, w = 8, h = 8, dpi = 400){
  if('ggplot2' %notin% loadedNamespaces()){ require(ggplot2)}
  myplot %T>%
    print() %T>%
    ggsave(filename = paste0(fname,".pdf"),plot = .,
           width = w, height = h, units = 'in',dpi = dpi, device = cairo_pdf) %T>%
    ggsave(filename = paste0(fname,".png"),plot = .,
           width = w, height = h, units = 'in',dpi = dpi) %T>%
    ggsave(filename = paste0(fname,".svg"),plot = .,
           width = w, height = h, units = 'in',dpi = dpi)

}

#' Write rds files in parallel
#'
#' @param object The data to be written
#' @param file The output filename
#' @param threads The number of cores to use
#' @author Martin Jung
#' @export
saveRDS.gz <- function(object, file, threads = parallel::detectCores() - 1 ){
  con <- pipe(paste0( "pigz -p", threads, " > ", file ), "wb")
  saveRDS(object, file = con)
  close(con)
}

#' Load rds files in parallel
#'
#' @param object The data to be written
#' @param file The output filename
#' @param threads The number of cores to use
#' @author Martin Jung
#' @export
readRDS.gz <- function(file, threads = parallel::detectCores() - 1){
  con <- pipe(paste0( "pigz -d -c -p", threads, " ", file))
  object <- readRDS(file = con)
  close(con)
  return(object)
}
Martin-Jung/naturepackage documentation built on Nov. 22, 2019, 12:04 a.m.