igraph degree distribution: count elements

[This article was first published on 0xCAFEBABE, 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.

Unfortunately, the degree.distribution() function of the igraph library returns the intensities of the distribution:

> g <- graph.ring(5)
> plot(g) 
> summary(g)
IGRAPH U--- 10 10 -- Ring graph
attr: name (g/c), mutual (g/x), circular (g/x)

So instead of having the number of elements, the density/intensities value is returned:

> degree.distribution(g)
[1] 0 0 1

You can easily verify this in the source code of the function:

> degree.distribution
function (graph, cumulative = FALSE, ...) 
{
    if (!is.igraph(graph)) {
        stop("Not a graph object")
    }
    cs <- degree(graph, ...)
    hi <- hist(cs, -1:max(cs), plot = FALSE)$intensities
    if (!cumulative) {
        res <- hi
    }
    else {
        res <- rev(cumsum(rev(hi)))
    }
    res
}


This caused me some minor issues, but the solution was easy. I simply created a new version of the function that is using $count instead of $intensities (BTW $intensities will be deprecated in R 3.0).

count.degree.distribution <- function (graph, cumulative = FALSE, ...) 
{
    if (!is.igraph(graph)) {
        stop("Not a graph object")
    }
    cs <- degree(graph, ...)
    hi <- hist(cs, -1:max(cs), plot = FALSE)$count
    if (!cumulative) {
        res <- hi
    }
    else {
        res <- rev(cumsum(rev(hi)))
    }
    res
}
Using it is identical to the original version:
> count.degree.distribution(g)
[1] 0 0 10

To leave a comment for the author, please follow the link and comment on their blog: 0xCAFEBABE.

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.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)