R/cytofQCreport.R

Defines functions cytofQCreport

Documented in cytofQCreport

#' Generate a cytofQC report
#'
#' @param x A SingleCellExperiment object generated by \code{\link{labelQC}}.
#' @param outDir The output directory (currently required).
#' @param sampName Basename of the output HTML file (if not provided, same as
#'   \code{outDir}).
#' @param runUMAP Logical value indicating whether or not to include a UMAP plot
#'   in the report. This plot can be beneficial for diagnostic purposes, but is
#'   time-consuming to generate.
#' @param ... Additions arguments that may be passed to the function.
#'
#' @return If successful, returns \code{TRUE} silently and generates the
#'   specified QC report.
#'
#' @examples
#' data("raw_data", package = "CATALYST")
#' x <- readCytof(raw_data, beads = "Beads", viability = c("cisPt1", "cisPt2"))
#' x <- labelQC(x, n = 500)
#' tmp <- tempdir()
#' cytofQCreport(x, tmp, 'example')
#' 
#' @importFrom rmarkdown render
#' @export
cytofQCreport <- function(x, outDir, sampName, runUMAP = TRUE, ...){
    
    if (!methods::is(x, "SingleCellExperiment")) {
        stop("x must be an object created with readCytof")
    }
    
    stopifnot(dir.exists(outDir))
    runUMAP <- as.logical(runUMAP)
    if(missing(sampName)){
        sampName <- basename(outDir)
    }
    labels <- factor(x$label, 
                     levels = c("cell", "GDPzero", "bead", "doublet", "debris"))
    out <- list(tech = x$tech, labels = labels)
    
    # temporarily store results on disk
    saveRDS(out, file = file.path(outDir, 'cytofQCdata_temp.rds'))
    
    template <- system.file("extdata", "template.Rmd", 
                            package = "cytofQC", mustWork = TRUE)
    
    ## Copy the template file to outDir
    file2Knit <- file.path(outDir, paste0(sampName,'.Rmd'))
    cp <- file.copy(template, file2Knit, overwrite = TRUE)
    if(!cp){
        stop("Template file was not able to be copied. ",
             "Do you need to set overwrite = TRUE " ,
             "or check write permissions?")
    }
    stopifnot(file.exists(file2Knit))
    
    ## Compile the document in the directory
    rmarkdown::render(
        file2Knit,
        output_dir = outDir,
        envir = new.env(),
        params = list(runUMAP = runUMAP)
    )
    message("done")
    
    # remove data and template
    file.remove(file.path(outDir, 'cytofQCdata_temp.rds'))
    file.remove(file2Knit)
    
    return(invisible(TRUE))
}
jillbo1000/cytofQC documentation built on Aug. 23, 2023, 9:47 p.m.