R/GenerateMetaTemplate.R

#' @title Flux metadata template-maker function.
#'
#' @description
#'
#' This function generates a metadata template for use with `flux`
#' class objects and writes it to a .csv, with the option to include
#' file and column names taken from a `flux` object and return that
#' object invisibly. See \link{ImportMeta} for details on what the
#' column names mean and how they should be filled.
#'
#' @param title   Title of the metadata file.
#' @param dir     Directory to generate the file.
#' @param flux    Flux file to start the template.
#' @param n_treat Number of treatment levels in the experiment.
#' @param write   T/F write the result to .csv?
#'
#' @details
#'
#' If a `flux` object is provided, the output file will have the `FILE`
#' and `COLUMN_NAME` columns filled in with information taken from
#' the `raw_data` slot of the flux object, and a flux object will be
#' returned invisibly.
#'
#' `n_treat`` will specify the number of treatment levels to associate
#' with the flux data. 'Treatment level' here is used in the statistical
#' sense, to refer to e.g. species identity, plot replicate, or site name
#' when SAMPLE is used to refer to individual trees, 'SUB_SAMPLE' to stems
#' on each tree, and 'SUB_SAMPLE_REPLICATE' to probe IDs that are on the
#' same stem on the same tree.
#'
#' @return
#'
#' If `write = T`, writes a .csv file to the directory specified by
#' `dir`. If a `flux` object is provided, invisibly returns a `flux`
#' object that can be designated for assignment. Otherwise, a data.frame.
#'
#' @family preprocess
#' @export
#' @examples
#' # Generates a blank template in the current working directory, with
#' # a treatment level for each of 'species', 'plot', and 'site. Leave
#' # out the .csv extension.
#' GenerateMetaTemplate(title = 'sapflux_project_metadata_May2018')
#' # Use with an existing flux object, does not change object:
#' GenerateMetaTemplate(title = 'mydata', flux = 'flux_with_my_data')
#' # Use with existing flux object, adds the metadata to the flux object
#' # as well as writing the csv:
#' new_flux <- GenerateMetaTemplate(title = 'mydata', flux = 'old_flux')
GenerateMetaTemplate <- function(title, dir = getwd(),
                                 flux = NULL, n_treat = 3, write = TRUE) {
  # Try to change working directory:
  # Input parameter checks:
  stopifnot(
    class(dir) == 'character' && length(dir) == 1,
    class(n_treat) == 'numeric' && length(n_treat) == 1
  )
  if (length(flux) > 0) CheckFluxObject(flux)
  # Valid columns:
  vc <- c('INCLUDE', paste('TREATMENT_', 1:n_treat, sep = ''),
          'SAMPLE', 'SUB_SAMPLE', 'SUB_SAMPLE_REPLICATE',
          'FILE', 'COLUMN_NAME', 'DBH',
          'DATE_INSTALLED', 'DATE_REMOVED')
  # Make the data.frame:
  meta <- data.frame(matrix(ncol = length(vc), nrow = 0), stringsAsFactors = F)
  colnames(meta) <- vc
  if (length(flux) > 0) {
    fils <- flux@source_files
    ncol <- unlist(lapply(flux@raw_data, function(x) length(colnames(x))))
    FILE <- rep(fils, ncol)
    COLUMN_NAME <- unlist(lapply(flux@raw_data, colnames))
    stopifnot(length(FILE) == length(COLUMN_NAME))
    INCLUDE <- rep('TRUE', length(FILE))
    meta <- merge(meta, data.frame(INCLUDE, FILE, COLUMN_NAME), all = T)
    cat('Returning meta as modified flux object.\n')
    flux@metadata <- meta
  }
  # Return:
  if (write) {
    rwd <- getwd()
    BadSetDir <- function(err) {
      setwd(rwd)
      cat('Bad `dir` input.\n')
      stop(err)
    }
    tryCatch(expr = { setwd(dir) },
             error = BadSetDir,
             warning = BadSetDir,
             finally = { invisible() })
    cat(paste('Writing', title, 'to:\n'), dir, '\n')
    write.csv(x = meta, file = paste(title, '.csv', sep = ""), row.names = F)
  }
  cat('Returning meta as dataframe.\n')
  setwd(rwd)
  if (length(flux) > 0) {
    invisible(flux)
  } else {
    invisible(meta)
  }
}
bmcnellis/sapflux documentation built on May 12, 2019, 10:27 p.m.