R/newMdaccReport.R

#' Build a new MDACC Report from a Template
#'
#' This pulls in a template report skeleton from
#' the package and names it using a prefix numbering
#' which should reflect the order in which the reports
#' are written. New reports are placed in their own
#' subfolders. This is largely a wrapper for
#' rmarkdown::draft() with some prespecified arguments.
#'
#' @param reportFilename Ideally informative text name for
#'     the report. This should not include a numerical
#'     prefix, as that should be autogenerated. There is
#'     no default here; you have to think of something.
#' @param reportPrefix If this is left as "default", the
#'     current directory will be checked for all files
#'     beginning with "r**_", where the "**" corresponds
#'     to two numbers. The largest number currently present
#'     will be incremented by one, and that new value will
#'     be used. Can be overridden.
#' @return invisible if the report subfolder and skeleton
#'     are successfully built.
#' @examples
#' newMdaccReport("preprocessData")
#' @export
newMdaccReport <- function(reportFilename, reportPrefix="default"){

  ## find project root

  projectRoot <- findKeithRoot()
  load(file.path(projectRoot, "projectInfo.RData"))

  if(reportPrefix == "default"){
    currentFiles <-
      dir(file.path(projectRoot, projectInfo$reportsFolder))
    extantReports <- grep("^r[[:digit:]]{2}_", currentFiles)
    if(length(extantReports) > 0){
      reportNumbers <-
        as.numeric(substr(currentFiles[extantReports], 2, 3))
      lastReport <- max(reportNumbers)
      if(lastReport < 9){
        reportPrefix <- paste0("r0", lastReport + 1, "_")
      }else{
        if(lastReport < 99){
          reportPrefix <- paste0("r", lastReport + 1, "_")
        }else{
          cat("too many reports!\n")
          break;
        }
      }
    }else{
      reportPrefix <- "r01_"
    }
  }

  reportName <- paste0(reportPrefix, reportFilename)
  fullReportPath <-
    file.path(projectRoot,
              projectInfo$reportsFolder,
              reportName)
  rmarkdown::draft(file = fullReportPath,
                   template = "report",
                   package = "keithUtils",
                   create_dir = TRUE,
                   edit = FALSE)

  reportRmd <-
    file.path(fullReportPath, paste0(reportName, ".Rmd"))
  temp <- readLines(reportRmd)
  prefixRow <- grep("reportPrefix <- ", temp)
  temp[prefixRow] <-
    paste0("reportPrefix <- \"", reportPrefix, "\"")
  writeLines(temp, con = reportRmd)

}
kabagg/keithUtils documentation built on May 20, 2019, 2:08 p.m.