R/ttImpute.R

Defines functions ttImpute

Documented in ttImpute

#' Treatment-treatment (tt) impute
#'
#' Impute the missing values for mat2 using tail imputation approach if mat1 has n1 or more quantified values
#' and mat2 has n2 or less quantified values, and vice versa if paired is set to be true. That is if mat2 has n1
#' or more quantified values and mat1 has n2 or less quantified values.
#'
#' @usage ttImpute(mat1, mat2, n1, n2)
#'
#' @param mat1 a matrix with rows correspond to phosphosites and columns correspond to replicates within treatment1.
#' @param mat2 a matrix with rows correspond to phosphosites and columns correspond to replicates within treatment2.
#' @param n1 an integer indicating n1 or more quantified values required for considering for imputation.
#' @param n2 an integer indicating n2 or less quantified values required for considering for imputation.
#' @param m a numeric number of for controlling mean downshifting.
#' @param s a numeric number of for controlling standard deviation of downshifted sampling values.
#' @param paired a flag indicating whether to impute for both treatment1 and treatment2 (default) or treatment2 only (if paired=FALSE).
#' @export
#'
ttImpute <- function(mat1, mat2, n1, n2, m=1.6, s=0.6, paired=TRUE) {

  # impute for mat2
  idx1 <- which(rowSums(!is.na(mat1)) >= n1 & rowSums(!is.na(mat2)) <= n2)
  print(paste("idx1:", length(idx1)))

  ms <- colMeans(mat2, na.rm = TRUE)
  sds <- apply(mat2, 2, sd, na.rm=TRUE)
  for(i in 1:ncol(mat2)) {
    mat2[idx1,i] <- rnorm(length(idx1), mean=(ms[i]-sds[i]*m), sd=(sds[i]*s))
  }

  if (paired == TRUE){
    # impute for mat1
    idx2 <- which(rowSums(!is.na(mat2)) >= n1 & rowSums(!is.na(mat1)) <= n2)
    print(paste("idx2:", length(idx2)))

    ms <- colMeans(mat1, na.rm = TRUE)
    sds <- apply(mat1, 2, sd, na.rm=TRUE)
    for(i in 1:ncol(mat1)) {
      mat1[idx2,i] <- rnorm(length(idx2), mean=(ms[i]-sds[i]*m), sd=(sds[i]*s))
    }

    return(cbind(mat1, mat2))
  } else {
    return(mat2)
  }
}
SydneyBioX/phosphoR documentation built on May 20, 2019, 12:58 a.m.