R/findModules.linkcommunities.R

Defines functions findModules.linkcommunities

Documented in findModules.linkcommunities

#' Find Modules with Network Adjacency Matrix Using Link Communities Algorithm
#' 
#' This function wraps a function iteratively to get modules from network adjacency
#' matrix using Link communities algorithm.
#' 
#' @inheritParams findModules.CFinder
#' 
#' @return  GeneModules = n x 3 dimensional data frame with column names as Gene.ID,
#' moduleNumber, and moduleLabel.
#' 
#' @importFrom magrittr %>%
#' @export
findModules.linkcommunities <- function(adj, nperm = 10, path, min.module.size = 30){
  
  # Note: For this function to work get the package linkcomm from CRAN
  
  # Error functions
  if(class(adj) != "matrix")
    stop('Adjacency matrix should be of class matrix')
  
  if(dim(adj)[1] != dim(adj)[2])
    stop('Adjacency matrix should be symmetric')
  
  if(!all(adj[lower.tri(adj)] == 0))
    stop('Adjacency matrix should be upper triangular')
  
  # Make adjacency matrix symmetric
  adj = adj + t(adj)
  adj[diag(adj)] = 0
  
  # Compute modules by permuting the labels nperm times
  all.modules = plyr::llply(1:nperm, .fun= function(i, adj, path, min.module.size){
    # Permute gene ordering
    ind = sample(1:dim(adj)[1], dim(adj)[1], replace = FALSE)
    adj1 = adj[ind,ind]
    
    # Find modules 
    mod = findModules.linkcommunities.once(adj1, min.module.size)
    
    # Compute local and global modularity
    adj1[lower.tri(adj1)] = 0
    Q = compute.Modularity(adj1, mod)
    Qds = compute.ModularityDensity(adj1, mod)
    
    return(list(mod = mod, Q = Q, Qds = Qds))
  }, adj, path, min.module.size)
  
  all.metrics = plyr::ldply(all.modules, .fun = function(x){
    data.frame(Q = x$Q, Qds = x$Qds)
  }) %>%
    dplyr::mutate(r = base::rank(Q)+base::rank(Qds))
  ind = which.max(all.metrics$r)
  
  mod = all.modules[[ind]]$mod
  
  return(mod)
}
Sage-Bionetworks/metanetwork documentation built on April 27, 2022, 7:42 a.m.