咨询 bipartite 库中求二分网络节点边权重总和的函数
bipartite Package) Hey there! Great question about summing edge weights for each node in your weighted bipartite network. Let me break down how to do this using the bipartite package, plus some straightforward base R methods that work perfectly too.
Step 1: Prepare Your Data for the bipartite Package
First, your current data is a data frame with country names in the first column. The bipartite package works best with a matrix format where rows represent one set of nodes (your PAIS_ORIGEN entries) and columns represent the other set (AFG, ETH, etc.). Let's convert your data:
# Load the bipartite package if you haven't already library(bipartite) # Convert your data frame to a bipartite matrix prueba_mat <- as.matrix(prueba[, -1]) # Remove the first column (PAIS_ORIGEN) rownames(prueba_mat) <- prueba$PAIS_ORIGEN # Set row names to the origin countries
Step 2: Calculate Total Edge Weights for Each Node
You have two easy options here—pick whichever fits your workflow:
Option 1: Base R's rowSums() / colSums() (Simple & Fast)
For your origin nodes (rows like USA, EU), use rowSums() to get the total of all edge weights per node:
# Calculate total weights for origin countries (rows) origin_totals <- rowSums(prueba_mat) # Check the total for USA (matches your manual calculation!) origin_totals["USA"] # Returns 11484.46
If you want totals for the destination countries (columns like AFG, ETH), use colSums() instead:
destination_totals <- colSums(prueba_mat)
Option 2: bipartite Package's specieslevel() Function (More Metrics)
The specieslevel() function in bipartite computes a range of node-level metrics, including the sum of edge weights. This is great if you want additional stats alongside the total weights:
# Calculate metrics for origin nodes (set level = "higher" for rows) origin_metrics <- specieslevel(prueba_mat, level = "higher", index = "sum") # View all origin node totals origin_metrics # Get just USA's total origin_metrics["USA", "sum"]
To get totals for destination nodes, switch level to "lower":
destination_metrics <- specieslevel(prueba_mat, level = "lower", index = "sum")
Quick Verification
Let's confirm the USA total matches your manual calculation:
6686.77 + 1726.46 + 834.16 + 2044.88 + 192.19 = 11484.46
Both methods above will return exactly this value, so you can trust the results!
内容的提问来源于stack exchange,提问作者Dario

