R/get_avg.R

Defines functions get_avg

Documented in get_avg

#' Order the entries in each matrix according to the average of rowMeans of all matrices combined.
#' @description Calculates average of rowMeans of all matrices in the list. Order the entries of all matrices according to this average. Called by "plot_hm"-function.
#' @param mat A list with matrices and additional information about the selected region. mat generated by "get_matrix"-function. Default value is NULL.
#' @return list with ordered matrix entries and additional information about the region entered in "get_matrix"-function. Will be used of "plot_hm"-function

get_avg = function(mat= NULL){
  
  ########## check mat input (got from "get_matrix" function) ##########
  if(is.null(mat)){
    stop("no mat inserted")
  }
  
  ########## calculate rowMeans for each matrix, Average and create id ##########
  nmats = length(mat)-5 ### number of matrices/ inserted bw-files

  mat_mean = lapply(seq_along(1:nmats), function(x){
    x = mat[[x]]                  
    rowMeans(x[,7:ncol(x)], na.rm = TRUE)
  })
  names(mat_mean) = names(mat)[1:nmats]
  mat_mean = data.frame(mat_mean)
  mat_mean$Avg = rowMeans(mat_mean)### add column for Average (Avg) of all rowMeans  
  mat_mean$id = paste(mat[[1]][,V1], mat[[1]][,V2], sep = '_') ### create id

  ########## merge input matrices with calculated Average by created id ##########
  
  for (i in 1:nmats){
    mat[[i]][,'id'] =  paste(mat[[i]][,V1], mat[[i]][,V2], sep = '_')
    mat[[i]] = merge(mat[[i]], mat_mean[,c('Avg','id')], by='id')
    mat[[i]] = mat[[i]][order(Avg),]
    mat[[i]] [, id := NULL]
  }
  mat_ssum =list()
  for (i in 1:nmats){
    mat_ssum[[i]] = colMeans(mat[[i]][,7:(ncol(mat[[i]])-1)], na.rm = TRUE)
  }
  matAvg = mat
  return(list(matAvg, mat_ssum))
}
ClaudiaRHD/chipAnalyser documentation built on June 18, 2020, 8:31 p.m.