[R] per-vertex statistics of edge weights

Gábor Csárdi csardi at rmki.kfki.hu
Thu Aug 16 02:55:10 CEST 2012


On Wed, Aug 15, 2012 at 2:04 PM, Sam Steingold <sds at gnu.org> wrote:
> I have a graph with edge and vertex weights, stored in two data frames:
>
> --8<---------------cut here---------------start------------->8---
> vertices <- data.frame(vertex=c("a","b","c","d"),weight=c(1,2,1,3))
> edges <- data.frame(src=c("a","a","b","c","d"),dst=c("b","c","d","d","a"),
>   weight=c(1,2,1,3,1))
> --8<---------------cut here---------------end--------------->8---
>
> I can create a graph from this data:
>
> --8<---------------cut here---------------start------------->8---
> library(igraph)
> graph <- graph.data.frame(edges, vertices = vertices, directed=FALSE)
> --8<---------------cut here---------------end--------------->8---
>
> what I want is to compute some edge weight stats (mean/median/max/min/)
> for each vertex.
>
> I guess I can do something like
>
> --8<---------------cut here---------------start------------->8---
>> sapply(vertices$vertex, function (v) mean(E(g)[inc(v)]$weight))
> Note: no visible global function definition for 'inc'
> [1] 1.333333 1.000000 2.500000 1.666667
> --8<---------------cut here---------------end--------------->8---

For me this gives

Error in mean(E(g)[inc(v)]$weight) :
  error in evaluating the argument 'x' in selecting a method for
function 'mean': Error in match(x, table, nomatch = 0L) : object 'g'
not found

which is no wonder, since 'g' is not defined.

> but I was wondering if this is TRT, given the correct answer with a
> scary note.

I am not sure what TRT is, but I would do this as

sapply(V(graph), function(v) mean(E(graph)$weight[incident(graph, v)]))

Your solution is somewhat messy, because vertices$vertex is actually a
factor, etc.

Gabor

[...]

-- 
Gabor Csardi <csardi at rmki.kfki.hu>     MTA KFKI RMKI



More information about the R-help mailing list