# Clean the environment rm(list = ls()) library(readxl) library(bipartite) library(igraph) library(openxlsx) matriz <- as.matrix(read_excel("data-METANETWORKS-QC.xlsx", sheet = "aggregated")) #change for others # Suppose you have already imported the matrix from Excel and it's named 'matriz' # Check the dimensions and names: dim(matriz) # Should show (number of fragments, number of interactions) rownames(matriz) # Make sure the fragments have names colnames(matriz) # Make sure the interactions have names rownames(matriz) <- paste0("Frag", 1:nrow(matriz)) library(igraph) # Create the bipartite graph from the matrix grafo_bipartito <- graph_from_incidence_matrix(matriz, weighted = NULL) # Check the number of nodes and their distribution: cat("Total nodes:", vcount(grafo_bipartito), "\n") print(table(V(grafo_bipartito)$type)) # Perform the unipartite projection proyeccion <- bipartite_projection(grafo_bipartito) # Extract the projection corresponding to the interactions grafo_interacciones <- proyeccion$proj2 # Check the number of nodes in the projection cat("Nodes in the interaction projection:", vcount(grafo_interacciones), "\n") # Calculate betweenness centrality (not automatically normalized) bc <- betweenness(grafo_interacciones, directed = FALSE, normalized = FALSE) # Normalize using the classical formula: # BC_normalized = BC / [((N - 1) * (N - 2) / 2)] N <- vcount(grafo_interacciones) bc_normalized <- bc / ((N - 1) * (N - 2) / 2) # Create a data frame with the results: bc_df <- data.frame( Interaccion = V(grafo_interacciones)$name, Betweenness = bc_normalized ) # Sort from highest to lowest betweenness bc_df <- bc_df[order(-bc_df$Betweenness), ] head(bc_df) bc_df View(bc_df) write.csv(bc_df, "betweenness_interacciones.csv", row.names = FALSE) # Degree degree_interactions <- colSums(matriz) degree_df <- data.frame( Interaccion = names(degree_interactions), Degree = degree_interactions ) # Sort from highest to lowest degree (optional) degree_df <- degree_df[order(-degree_df$Degree), ] degree_df View(degree_df) write.csv(degree_df, "degree_interacciones.csv", row.names = FALSE) # Merge the degree and betweenness tables based on the "Interaccion" column tabla_completa <- merge(degree_df, bc_df, by = "Interaccion", all = TRUE) # Sort the table from highest to lowest by Betweenness tabla_completa <- tabla_completa[order(-tabla_completa$Betweenness), ] # View the table in RStudio View(tabla_completa) # Export the table to a CSV file write.csv(tabla_completa, "tabla_completa_interacciones.csv", row.names = FALSE) install.packages("openxlsx") library(openxlsx) # Export the table to an Excel file write.xlsx(tabla_completa, "tabla_completa_interacciones.xlsx", rowNames = FALSE)