create eigenvalues and eigenvectors from laplacian matrix then plot to cluster plot in r

main.r
# Generate a Laplacian matrix
library(igraph)

# Create a sample graph
graph <- make_graph("Zachary")

# Get Laplacian matrix
laplacian <- graph.adjacency(as_adjacency_matrix(graph), mode = "undirected")$laplacian

# Calculate eigenvalues and eigenvectors
eigen_data <- eigen(laplacian)
eigenvalues <- eigen_data$values
eigenvectors <- eigen_data$vectors

# Perform clustering with k-means
k <- 2
clustering <- kmeans(eigenvectors[, 2:k], centers = k)

# Plot the graph with clustering results
plot(graph, vertex.color = clustering$cluster)
541 chars
21 lines

This code snippet first generates a Laplacian matrix from a sample graph using the igraph package in R. Then, it calculates the eigenvalues and eigenvectors of the Laplacian matrix. Next, it performs clustering using k-means on the eigenvectors (excluding the first eigenvector). Finally, it plots the graph with each vertex colored according to the cluster it belongs to.

gistlibby LogSnag