R/coregulationgraphfunctions.R

Defines functions BuildGraphDataFrame BuildCoRegulationGraph

Documented in BuildCoRegulationGraph BuildGraphDataFrame

#' Construct a co-regulation graph where nodes are analytes, and edges
#' are present between nodes and edges that meet the processing cutoffs. 
#' The graph generated by this function is undirected and
#' is an igraph object.
#' @param inputResults A data frame containing the analyte names for each model
#' and the coefficients, p-values, and R^2 values.
#' @param vertexSize Width of each vertex in pixels
#' @export
BuildCoRegulationGraph <- function(inputResults, vertexSize=15){
  
  # Set vertex colors.
  color <- "gray"
  framecolor <- "gray"
  
  # Build each data frame.
  graph_df <- BuildGraphDataFrame(inputResults)
  edge_df <- graph_df$edges
  node_df <- graph_df$nodes
  
  # Set parameters.
  node_df <- node_df[!duplicated(node_df$node),]
  node_df$size <- vertexSize
  node_df$color <- color
  node_df$frame.color <- framecolor
  
  # Build and return the graph.
  final_graph = igraph::graph_from_data_frame(edge_df, vertices = node_df)
  return(final_graph)
}

#' Construct a data frame that includes all information needed to build an igraph
#' object. This includes the names of the two co-regulated analytes, whether the
#' analytes have a positive or negative co-regulation, and the shape of the analytes.
#' @param inputResults A data frame containing the analyte names for each model
#' and the coefficients, p-values, and R^2 values.
BuildGraphDataFrame <- function(inputResults){
  
  graph_data_frame <- data.frame()
  if(nrow(inputResults) > 0){
    # Add the analytes to the data frame.
    edge_df = data.frame(from = inputResults$Analyte1, 
                         to = inputResults$Analyte2)
    
    # Add the weights and corresponding colors.
    edge_df$weight = 1
    edge_df$weight[which(inputResults$interaction_coeff < 0)] = -1
    edge_df$color = "blue"
    edge_df$color[which(inputResults$interaction_coeff < 0)] = "red"
    
    # Build the vertex graph, including the shape of each vertex.
    node_df = data.frame(node = unique(inputResults$Analyte1), 
                         shape = "circle")
    node_df_c2 = data.frame(node = unique(setdiff(inputResults$Analyte2, 
                                                  inputResults$Analyte1)), 
                            shape = "circle")
    node_df = rbind(node_df, node_df_c2)
    graph_data_frame <- list(edges = edge_df, nodes = node_df)
  }
  
  # Return the data frame.
  return(graph_data_frame)
}
ncats/MultiOmicsGraphPrediction documentation built on Aug. 23, 2023, 9:19 a.m.