R/normalize_plates.R

Defines functions normalize_plate normalize_plates

Documented in normalize_plate normalize_plates

#' Normalize a single plate
#'
#' @param df The plate's data frame.
#' @param src.var The \code{enquo}'d variable to be normalized.
#' @param dst.var The \code{enquo}'d variable to store normalized values in.
#' @param ... Ignored additional parameters.
#' @importFrom magrittr %>%
#' @importFrom dplyr enquo mutate select group_by group_modify
#' @importFrom rlang :=
#'
#' @return The normalized plate data frame.
normalize_plate <- function(df, src.var, dst.var, ...) {
  # Calculate the normalizing factor as the mean of the src.var value of all standards
  standard <- standards(df) %>%
    select(!! src.var) %>%
    unlist %>%
    mean
  df %>%
    mutate((!! dst.var) := (!! src.var) / standard)
}
#' Normalize replicates
#'
#' @param df The data frame to normalize.
#' @param plate.var The variable that delimits plates (default: \code{Plate}).
#' @param src.var The variable to normalize (default: \code{Luminescence}).
#' @param dst.var The variable in which to store the normalized result (default: \code{Normalized}).
#' @param ... Unused additional arguments, necessary for the correctness of the function signature.
#'
#' @return The data frame with each \code{Plate}'s values normalized by the average of that \code{Plate}'s \code{standards} and placed in \code{Normalized}.
#' @export
#'
#' @examples
#' normalize_plates(some.df)
normalize_plates <- function(df, plate.var = Plate, src.var = Luminescence, dst.var = Normalized) {
  # enquo the variables so we can pass them around as objects (promises) without issue
  plate.var <- dplyr::enquo(plate.var)
  src.var <- dplyr::enquo(src.var)
  dst.var <- dplyr::enquo(dst.var)
  # Create a closure instead of using normalize_plate directly so we can apply the correct src.var and dst.var
  normalize <- function(x, ...) normalize_plate(x, src.var = src.var, dst.var = dst.var, ...)
  # Call the closure on each grouping of plate.var
  df %>%
    group_by(!! plate.var) %>%
    group_modify(normalize) %>%
    ungroup
}
Aehmlo/lucy documentation built on Oct. 30, 2019, 4:09 a.m.