R/humanFSformat.R

Defines functions humanFSformat

humanFSformat <- function(filesize, format = "B") {
  # Reformat filesize string.
  #
  # Arguments:
  #   filesize {char} or {numeric} -- filesize in format '## KB', '## MB', or '## GB' format,
  #                                   where ## represents any number, or in numeric format.
  #
  # Keyword Arguments:
  #   format {char} -- desired output format, one of 'B', 'KB', 'MB', 'GB' (default: "B")
  #
  # Returns:
  #   numeric -- filesize in desired format
  
  options(scipen = 999)  # Turn off scientific notation
  stopifnot(format %in% c("B", "KB", "MB", "GB"))
  
  # Get size in bytes if input format is, for example, "1 GB", ".7 MB", "2KB"
  if(is.character(filesize)) {
    mult = rep(NA, length(filesize))
    mult[grepl("KB", filesize, ignore.case = TRUE)] = 1000
    mult[grepl("MB", filesize, ignore.case = TRUE)] = 1000000
    mult[grepl("GB", filesize, ignore.case = TRUE)] = 1000000000
    filesize = as.numeric(gsub("(\\d+\\.{0,1}\\d*).*", "\\1", filesize)) * mult
  }
  
  # Format according to user-specified B, KB, MB or GB and return
  if(toupper(format) == "B") {
    return(filesize)
  } else if(toupper(format) == "KB") {
    return(filesize / 1000)
  } else if(toupper(format) == "MB") {
    return(filesize / 1000000)
  } else if(toupper(format) == "GB") {
    return(filesize / 1000000000)
  } else { return(filesize) }
}
tsouchlarakis/rdoni documentation built on Sept. 16, 2019, 8:53 p.m.