-2

I have this network graph in R:

library(igraph)

# create the data frame
my_data <- data.frame(to = c(1,2,3,4,2,4), from = c(2,2,2,2,6,5))

# create the igraph object
my_graph <- graph_from_data_frame(my_data, directed = FALSE)

# plot the graph
plot(my_graph)

I also have this data frame of values:

set.seed(123)
values = data.frame(id = c(1,2,3,4,5,6,7,8,9,10), value = rnorm(10,100,10))

> values
   id     value
1   1 101.19245
2   2 102.43687
3   3 112.32476
4   4  94.83936
5   5  90.07493
6   6 116.75697
7   7  95.58837
8   8  92.76934
9   9  87.63727
10 10  87.15284

My Question: Based on the values data frame, I want to sum the values of all nodes in this graph. I tried to do this like this:

# extract vertices 
vertices <- V(my_graph)$name

# match vertices
vertex_values <- values$value[match(vertices, values$id)]

# sum up the values
sum_vertex_values <- sum(vertex_values)

I am doing this correctly?

Thanks!

Note: I think this is how you can sum specific the values of specific nodes

# sum values of nodes 1,5,6
nodes_to_sum <- c(1, 5, 6)
node_values <- subset(values, id %in% nodes_to_sum)
sum_values <- sum(node_values$value)
plot(induced.subgraph(graph=my_graph,vids=nodes_to_sum))

# sum values for neighbors of a specific node
n = neighbors(my_graph, 2)
neighbor_values <- subset(values, id %in% neighbor_nodes)
sum_values <- sum(neighbor_values$value)
plot(induced.subgraph(graph=my_graph,vids=n ))

References:

zx8754
  • 52,746
  • 12
  • 114
  • 209
stats_noob
  • 5,401
  • 4
  • 27
  • 83
  • 1
    Your code works fine, what is the issue? – zx8754 Mar 03 '23 at 08:56
  • @ zx8754 : thank you for your reply! at times when I ran the code, I would manually compare the sum vs the sum from the code ... and the results would not match. I was trying to see if someone could confirm if the logic is correct? – stats_noob Mar 03 '23 at 09:01

1 Answers1

1

Consider.

library(igraph)
my_data <- data.frame(to = c(1,2,3,4,2,4), from = c(2,2,2,2,6,5))
my_graph <- graph_from_data_frame(my_data, directed = FALSE)

# Observe the name of vertices 5,6 are actually "6", "5", as shown below.
V(my_graph)$name
#[1] "1" "2" "3" "4" "6" "5"

# Therefore try,
my_graph <- graph_from_data_frame(my_data, directed = FALSE, vertices = seq(nrow(my_data))

Perhaps this caused confusion when manually comparing the sum with the sum from the code.

Deserves a place in the igraph inferno.

clp
  • 1,098
  • 5
  • 11