R/NC_remove.R

Defines functions NC_remove

Documented in NC_remove

#' Natural connectivity analysis
#' @param input Network adjacency matrix. Can be generated by \code{\link{network_analysis}}
#' @param num Max number of removed nodes. Default: Automatically match max number that can be removed.
#' @param seed Random seed Number to be set. Default: 1. See in \code{\link{set.seed}}
#'
#' @return NC_remove returns data frame with removed nodes and corresponding natural connectivity
#' @export
#' @author  Wang Ningqi<2434066068@qq.com>
#'
#'
#' @importFrom utils txtProgressBar setTxtProgressBar
#' @examples
#' {
#'   ### Data preparation ###
#'   data("Two_group")
#'
#'   ### One input network analysis ###
#'   network_results <- network_analysis(
#'     taxobj = Two_group,
#'     taxlevel = "Base",
#'     reads = FALSE,
#'     n = 10,
#'     threshold = 0.6
#'   )
#'
#'   network_matrix <- as.data.frame(network_results[[3]])  # Complete adjacency matrix
#'
#'   # Check initial natural connectivity
#'   nc <- nc(network_matrix)
#'
#'   # Conduct natural connectivity analysis
#'   nc_remove <- NC_remove(input = network_matrix)
#'   head(nc_remove)
#'   tail(nc_remove)
#'
#'   # Set target number for natural connectivity analysis
#'   nc_remove <- NC_remove(input = network_matrix, num = 400)
#' }
NC_remove=function(input,num,seed=1){
  max_num=(c(rownames(input)[rowMeans(abs(input))>0],colnames(input)[colMeans(abs(input))>0]) %>%
             unique()%>% length())/2
  if(missing(num)){num=max_num-1}
  inputnum=num
  if(num>(max_num-1)){num=max_num-1}
  natural_connectivity <- nc(input)
  pb <- txtProgressBar(style=3)
  i=1;i_remove=0
  set.seed(seed)
  while (i<=num) {
    remove_node <- sample(1:dim(input)[1],i)
    adj_matrix2 <- input[-remove_node,-remove_node]
    natural_connectivity_remove <- nc(adj_matrix2)
    natural_connectivity <- c(natural_connectivity, natural_connectivity_remove)
    i_remove=c(i_remove,i)
    setTxtProgressBar(pb, i/num)
    end_time <- Sys.time()
    i=i+1
  }
  if(i<inputnum){i_remove[i:inputnum]=i:inputnum;natural_connectivity[i:inputnum]=0}
  Sys.sleep(1)
  close(pb)
  plot(i_remove,natural_connectivity,xlab = "Removed nodes number",ylab = "Natural connectivity")
  data.frame(i_remove,natural_connectivity) %>% return()
}

Try the LorMe package in your browser

Any scripts or data that you put into this service are public.

LorMe documentation built on Sept. 13, 2024, 9:07 a.m.