convert igraph list into a dataframe with the node names instead of the numbers in r

You can convert an igraph object to a dataframe in R using the as.data.frame() function. However, to replace the node numbers with node names, you need to specify the vertices and edges attributes of the igraph object.

Here is a sample code:

main.r
# Load necessary libraries
library(igraph)

# Create a sample graph
g <- graph(c(1,2, 2,3, 3,4, 4,1), directed=FALSE)

# Set vertex names
V(g)$name <- c("A", "B", "C", "D")

# Convert edges to dataframe
df <- as.data.frame(get.edgelist(g))

# Replace column names
colnames(df) <- c("source", "target")

# Get vertex names for source and target
df$source_name <- V(g)$name[match(df$source, V(g))]
df$target_name <- V(g)$name[match(df$target, V(g))]

# Remove columns with node numbers
df <- df[, c("source_name", "target_name")]

# Print the resulting dataframe
print(df)
571 chars
25 lines

This will output:

main.r
  source_name target_name
1             A            B
2             B            C
3             C            D
4             D            A
142 chars
6 lines

Note that this code assumes that the vertex names are stored in the name attribute of the igraph object. You may need to adjust the code if your vertex names are stored in a different attribute.

related categories

gistlibby LogSnag