Geometric Random graphs
[This article was first published on Random Miner, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Some days ago a friend of mine asked how much i knew about graph-theory. My answer: nothing. Anyway, i was able to read a little bit on Random Geometric graphs, so i came with this little function to help visualize these things:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
get.dist = function(x) | |
{ | |
sqrt(x[1]^2 + x[2]^2) | |
} | |
get.pairs = function(N) | |
{ | |
M = matrix(0, nrow = N * (N - 1)/2, ncol = 2) | |
x = 1:N | |
k = 1 | |
for (i in head(x, -1)) | |
{ | |
for (j in (i + 1):(length(x))) | |
{ | |
M[k, ] = c(i, j) | |
k = k +1 | |
} | |
} | |
M | |
} | |
create.graph = function(N = 100, d = 0.3) | |
{ | |
rnd.points = matrix(runif(2 * N), ncol = 2) | |
perms = get.pairs(N) | |
Edges = apply(perms, 1, FUN = function(x){ | |
vec.diff = rnd.points[x[1], ] - rnd.points[x[2], ] | |
get.dist(vec.diff) | |
}) | |
res = cbind(Edges, perms) | |
colnames(res) = c('E', 'V1', 'V2') | |
list(M = res, N = N, d = d, pts = rnd.points) | |
} | |
plot.graph = function(graph.obj) | |
{ | |
N = graph.obj$N | |
d = graph.obj$d | |
M = graph.obj$M | |
rnd.points = graph.obj$pts | |
caption = paste('G(N, d) : (', N, ', ', d, ')', sep = '') | |
plot(rnd.points, type = 'p', pch = 21, bg = 'red', main = caption, cex = 1.5) | |
for (r in 1:nrow(M)) | |
{ | |
if (M[r, 1] <= d) | |
{ | |
v1 = M[r, 2] | |
v2 = M[r, 3] | |
arrows(rnd.points[v1, 1], rnd.points[v1, 2], rnd.points[v2, 1], rnd.points[v2, 2], angle = 0) | |
} | |
} | |
} | |
draw.graph = function(N = 100, d = 0.3) | |
{ | |
g = create.graph(N, d) | |
plot.graph(g) | |
} |
There are some pretty good packages on this subject: igraph, statnet, sna, just to cite some.
Enjoy it!
To leave a comment for the author, please follow the link and comment on their blog: Random Miner.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.