Replace Elements in a List with Another List

I am working with R programing language.

Suppose I have the following code that randomly generates a network graph:


#create file from which to sample from
x5 <- sample(1:100, 1000, replace=T)
#convert to 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)

c = cbind(a,b)
#create dataframe
c = data.frame(c)
#rename column names
colnames(c) <- c("a","b")

graph <-, directed=F)
graph <- simplify(graph)


enter image description here

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?


I think you can get the sum of the weights of the neighbors with

sapply(all_neighbors, function(vec) sum(weight_data[vec,"weight"]))

I am not familiar with objects produced by igraph functions, so I may not be correct.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.