I am working with R programing language.
Suppose I have the following code that randomly generates a network graph:
library(igraph)
#create file from which to sample from
x5 <- sample(1:100, 1000, replace=T)
#convert to data frame
x5 = as.data.frame(x5)
#create first file (take a random sample from the created file)
a = sample_n(x5, 900)
#create second file (take a random sample from the created file)
b = sample_n(x5, 900)
#combine
c = cbind(a,b)
#create dataframe
c = data.frame(c)
#rename column names
colnames(c) <- c("a","b")
graph <- graph.data.frame(c, directed=F)
graph <- simplify(graph)
plot(graph)
Suppose I assign a weight to each node in this graph:
weight_data = data.frame(id = 1:100, weight = rnorm(100, 20,2))
Now, I want to run a "search" this graph. I want to return nodes such that:
- The node has more than 10 neighbors
- The weight of the node is bigger than the sum of the weight of its 10 neighbors.
I tried the following approach:
# find number of neighbors of graph
neighbors = V(graph)
#make a file of neighbors
neighbor_file = data.frame(V = as.vector(V(graph)),
Count = degree(graph, v = V(graph), mode = "out"))
#select nodes with at least 10 neighbors
ten_neighbor = neighbor_file[which(neighbor_file$Count > 10), ]
# find those 10 neighbor
all_neighbors = neighborhood(graph, order = 1, V(graph) %in% ten_neighbor$V)
However, from here - I do not know how I could sum the weights for all the neighbors for each of these nodes to check if the condition is satisfied. I tried this code but got an error:
mapply(function(a,b) a[b], all_neighbors, weight_data$weight)
Error in simple_vs_index(x, lazy_eval(args[[1]])) :
Unknown vertex selected
Had this worked, I would have replaced all element in the list with their node weights, summed these node weights, and then determined if the condition was satisfied.
Can someone please show me how to fix this?
Thanks!