[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [igraph] Sorting a graph or assigning attributes based on vertex nam
From: |
Gábor Csárdi |
Subject: |
Re: [igraph] Sorting a graph or assigning attributes based on vertex names |
Date: |
Wed, 31 Oct 2012 12:27:07 -0400 |
Hi,
you can actually assign the bucket attributes all at once, and this is
relatively fast, the graph is only copied once.
## Some example data
g <- degree.sequence.game(sample(2:10), method="simple")
buckets <- letters[seq_len(vcount(g))]
## Assign buckets
V(g)$bucket[order(degree(g), decreasing=TRUE)] <- buckets
## Check result
V(g)$bucket
## This gives the same solution as your function:
V(foo(g, buckets))$bucket
Gabor
On Mon, Oct 29, 2012 at 2:45 PM, Alan Labouseur <address@hidden> wrote:
> Hi. I'm trying to assign a "bucket" attribute (from a vector of buckets) to
> each vertex based on the position of the vertex degree when sorted. My
> initial approach seems to work nicely up to the point of setting all of the
> vertex attributes in the graph. After replicating the bucket vector so that
> it's long enough to cover all of the vertices in g, I preserve g's vertex IDs
> in the "name" attribute. Then I sort the vertices based on their degree. Then
> I take only the "names" portion of the sorted vector which represents the
> vertex IDs in the order I want to match them up to the buckets vector (bv).
> But from that point it's horribly slow because of that for loop and
> constantly reassigning the entire graph (g) after each set.vertex.attribute.
> I bet there's a better way. I appreciate any help or ideas. Thanks. Here's
> the code:
>
> foo <- function(g, buckets) {
> # REPlicate buckets so that it's long enough to cover all the vertices in
> g.
> bv <- rep(buckets, (vcount(g) %/% length(buckets))+1)
> #
> # Label each vertex with its current id.
> V(g)$name <- V(g) #
> V(g)[1:20]$name
> # Sort on degree.
> sortedDegrees <- sort(degree(g), decreasing=TRUE) #
> sortedDegrees[1:20]
> # Get the vertices in degree-sorted order.
> sortedVertexIDs <- attr(sortedDegrees, "names", exact=TRUE) #
> sortedVertexIDs[1:20]
> #
> # Set the "bucket" attribute of every (sorted) vertex in g to the
> corresponding (replicated) value in the bv.
> i <- 1
> for (vid in sortedVertexIDs) {
> g <- set.vertex.attribute(g, "bucket", vid, bv[i])
> i <- i + 1
> }
> #
> # Return the entire graph.
> g
> }
>
> Thanks!
> -Alan
>
>
> _______________________________________________
> igraph-help mailing list
> address@hidden
> https://lists.nongnu.org/mailman/listinfo/igraph-help
--
Gabor Csardi <address@hidden> MTA KFKI RMKI