R/cellnetwork3_CellComm.R

Defines functions cellnetwork3

Documented in cellnetwork3

#' Calculate cell network based on number of interactions in the pairs.
#'
#' Select the pairs that have more elements than the threshold and create a graph
#' of the interactions.
#'
#' @param result matrix?; the interactions for each pair, plus the pvalue
#' column, as generated by the calculatePvalue function.
#' @param threshold numeric; the number of elements in the pair for it to be
#' selected.
#'
#' @return list; the graph generated and the pairs.
#'
#' @export
cellnetwork3 <- function(result, threshold){
  print('split')
  x <- split(result, result[,c('celltype1','celltype2')])
  #x <- x[lapply(x,  function(y){length(as.vector(y$pair))}) > threshold] #decide unique pairs or total pairs...
  #x <- x[lapply(x,  function(y){length(unique(y$pair))}) > threshold] #decide unique pairs or total pairs...
  #x <- x[lapply(x,  function(y){length(unique(y$pair))}) > 0] #decide unique pairs or total pairs...
  #xx <- rbind.fill(lapply(x, function(y){data.frame(cell1=unique(as.vector(y$cell1)), cell2=unique(as.vector(y$cell2)), connections=nrow(y))}))
  # Decide unique pairs or total pairs...
  x <- x[lapply(x,  function(y){length(unique(y$pair))}) > threshold]

  print('rbind.fill')
  xx2 <- plyr::rbind.fill(lapply(x, function(y){
    data.frame(celltype1=as.vector(y$celltype1),
               celltype2=as.vector(y$celltype2),
               weight=nrow(y))}))
  print('rbind.done')
  #xx$weight <- as.vector(xx$connections) / max(as.vector(xx$connections))
  #xx$weight <- as.vector(xx$connections)
  #xx2 <- xx[which(xx$weight > threshold),] #if any two cells have more then 20 pairs/connectios, they are interacting...

  graph <- igraph::graph.data.frame(xx2, directed = FALSE)
  igraph::V(graph)$size <- igraph::degree(graph)
  #V(graph)[rownames(cellrouter@sampTab[V(graph)$name,])]$assignment <- as.vector(cellrouter@sampTab[V(graph)$name,'cellStates'])
  #V(graph)$color=V(graph)$assignment
  igraph::E(graph)$celltype1 <- as.vector(xx2$celltype1)
  igraph::E(graph)$celltype2 <- as.vector(xx2$celltype2)

  return(list(graph=graph, pairs=x))
}
edroaldo/fusca documentation built on March 1, 2023, 1:43 p.m.