R/applyFunInPairwiseManner.R

Defines functions applyFunInPairwiseManner

Documented in applyFunInPairwiseManner

#' Apply function in pairwise cases manner given data frame plus annotation
#'
#' Allows application of any function in pairwise cases manner as long as the inputs to the function can be a subset of inputed data frame and annotation. It creates iterative data frame and annotation cases in pairwise manner and supplements these iterations to the FUN. More parameters to FUN can also be supplied.
#'  
#' @param df A data frame where columns represent samples  
#' @param anno Annotation. Make sure row.names(anno) correspond to sample names in the same order as in df and that it has a unique cases colum named "condition" in the first column, i.e. anno[,1].
#' @param FUN The function we want to supply. It takes in a pair-wise compliant subset of original df and anno.
#' @param ... Ellipsis. Other arguments to be supplied to the FUN.
#' @return A list where elements are outputs of FUN in a pairwise fashion. 
#' @export

applyFunInPairwiseManner <- function(df, anno, FUN, ...){
  if(!(colnames(anno)[1] == "condition")){
    stop("anno[,1] is not named 'condition'. Make sure it is. Exiting")
  }
  cases <- unique(as.character(anno$condition))
  l_out <- list()
  com <- combn(length(cases),2)
  cases_to_num <- as.numeric(as.factor(as.character(anno$condition))) # numbers corspond to conditions
  anno <- cbind(anno, cases_to_num)
  for(i in 1:ncol(com)){
    df_i <- cbind(df[,anno$cases_to_num==com[,i][1]],
                  df[,anno$cases_to_num==com[,i][2]])
    a_i <- as.data.frame(
      cbind(anno[anno$cases_to_num==com[,i][1]|anno$cases_to_num==com[,i][2],]$condition,
            row.names(anno[anno$cases_to_num==com[,i][1]|anno$cases_to_num==com[,i][2],]))
    )
    a_i <- changeTypeOfColumns(df=a_i, rangeOfColumns = 1:2, type = "character")
    out_i <- FUN(df_i, a_i, ...)
    l_out <- lappend(l_out, out_i)
    names(l_out)[length(l_out)] <- paste(unique(a_i[,1])[1], "vs", unique(a_i[,1])[2], sep = " ")
    #print(paste(unique(a_i[,2])[1], "vs", unique(a_i[,2])[2], sep = " "))
  }
  return(l_out)
}
msxakk89/dat documentation built on Aug. 3, 2020, 6:39 p.m.