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: