R/data_management.R

Defines functions check_file load_data save_data

Documented in check_file load_data save_data

#' Save Data to Given File
#'
#' @param data the dataframe to be saved
#' @param out_file the full path of the saved file
#' @param prompt if true, prompts the user to confirm overwrite
#'
#' @return none
#'
#' @examples
#' \dontrun{
#'  saveData(files,"path/to/newfile.csv")
#' }
save_data <- function(data, out_file, prompt=TRUE) {
  if (file.exists(out_file) & prompt == TRUE) {
    if (tolower(readline(prompt = "Output file exists, would you like to overwrite? y/n: ")) == "y") {
      utils::write.csv(data, file = out_file, row.names = F, quote = F)
    }
  } 
  else { utils::write.csv(data, file = out_file, row.names = F, quote = F) }
}


#' Load .csv or .Rdata file 
#'
#' @param file the full path of the file to load
#'
#' @return data extracted from the file
#' @export
#'
#' @examples
#' \dontrun{
#'   loadData("path/to/newfile.csv")
#' }

load_data <- function(file) {
  ext <- strsplit(basename(file), split="\\.")[[1]][-1]
  if (ext == "csv") { return(utils::read.csv(file)) }
  else{ stop("Error. Expecting a .csv file.") }
}


#' Check for files existence and prompt user if they want to load
#'
#' @param file the full path of the file to check
#'
#' @return a boolean indicating wether a file was found 
#'             and the user wants to load or not
#' @importFrom methods is
#'
#' @examples
#' \dontrun{
#'   checkFile("path/to/newfile.csv")
#' }
check_file <- function(file) {
  if (!is.null(file) && file.exists(file)) {
    date <- exifr::read_exif(file, tags = "FileModifyDate")[[2]]
    date <- strsplit(date, split = " ")[[1]][1]
    if (tolower(readline(prompt = sprintf("Output file already exists and was last modified %s, would you like to load it? y/n: ", date)) == "y")) {
      return(TRUE)
    }
  }
  FALSE
}
icr-ctl/animl documentation built on July 5, 2025, 6:44 a.m.