You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言中Incidence Matrix(CSV)转Edge List格式报错求助

Got it, let's fix this incidence matrix to edge list conversion issue. The error you're seeing happens because the network package's incidence matrix handling expects a specific structure (often for bipartite graphs with binary ties), but your matrix has weighted values and we just need to extract non-zero entries directly. Here's how to get exactly the edge list you want:

Step 1: Read and prepare your incidence matrix

First, read the CSV and convert it to a matrix to preserve row/column names properly:

# Read the file, keep row names and original column names
y <- read.csv("C:/.../some.csv", header = TRUE, row.names = 1, check.names = FALSE)
# Convert to matrix for easier reshaping
y_mat <- as.matrix(y)

Step 2: Reshape to edge list (filter non-zero values)

We can use either base R + reshape2 or the tidyverse approach to turn the wide matrix into a long edge list, then remove entries with 0 weight:

Option 1: Using reshape2

# Install the package if you haven't already
# install.packages("reshape2")
library(reshape2)

# Melt the matrix into long format
el_long <- melt(y_mat, varnames = c("Node1", "Node2"), value.name = "Weight")
# Filter out rows where weight is 0
el_clean <- el_long[el_long$Weight != 0, ]
# Reorder columns to match your desired output
el_final <- el_clean[, c("Node1", "Node2", "Weight")]

Option 2: Using tidyverse (tidyr/dplyr)

# Install the package if you haven't already
# install.packages("tidyverse")
library(tidyverse)

el_final <- y_mat %>%
  as.data.frame() %>%
  rownames_to_column("Node1") %>%
  pivot_longer(cols = -Node1, names_to = "Node2", values_to = "Weight") %>%
  filter(Weight != 0) %>%
  select(Node1, Node2, Weight)

Step 3: Export the final edge list

Write the cleaned edge list to your desired CSV file:

write.csv(el_final, file = "C:/.../result_incidence.csv", row.names = FALSE)

Why your original approach failed

The error from the network function occurs because network.incidence is built to create bipartite graph objects, and it expects the incidence matrix to represent binary connections between two disjoint node sets. Your weighted values and the default directedness settings confused the function, leading to the "empty head/tail lists" error. Since you just need to extract non-zero weighted ties directly, reshaping the matrix is simpler and avoids package-specific constraints.

The output from the code above will match exactly the edge list format you requested:

Node1,Node2,Weight
a,A,1
a,C,3
a,D,1
b,D,2
c,A,3
c,B,2
c,D,1

内容的提问来源于stack exchange,提问作者C.H.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:05:38