Degree of vertex

hello
i want to ask a question about graphs in R , in a huge a graph if i want to work in a specific nodes and i want to know if these nodes are connected to specific node there is any function can help , for example i have a node number 1,2 and i want to no if these two nodes connect to node number 3(there is edge between these nodes and node number 3), i know the function "neighbors" but i want to know if there is way that i can compare between the neighbors of node 1 and neighbors of node 2 ???

Here's a function that takes a graph and a vector of vertices and returns the index of each vertex that is connected to all of the input vertices.

all_connected = function(graph, vertices) {
  which(sapply(V(x), function(t) {
    all(vertices %in% neighbors(graph, t))
    }))
}

Now to apply the function:

# Create a graph
set.seed(2)
x = sample_gnm(20, 50)
all_connected(x, 1:2)
## [1]  6 11
1 Like

Hi Ahmad, welcome to community.rstudio.com!

I hope Joels' reply helps you.

But if it doesn't, and for questions in the future, be sure when you ask a programming question like this to supply a reproducible example. This will help fine tune your question to make it easier to help you. (Not sure what a reproducible example is? FAQ: What's a reproducible example (`reprex`) and how do I do one?)

1 Like

thank you so much ,the function was really useful ,now in the graph in the photo i attached if i want to know for how many nodes that node 10 connected in the level 3 in the graph and if i want to compare between the nodes that connected to node 10 and 8 in level 3 , how i can do it (if i want the result as a number or list of the nodes )???

Rplot

Have a look at the following stack overflow post:

Here's a nice visual to give you a sense of the graph they are working with: https://stackoverflow.com/a/36675845/2093559

You can see Node A has 6 level 3 connections.

And then here's a method to get to that number: https://stackoverflow.com/a/36554882/2093559 (just count the number of occurances of 3 in rank)


This also brings up a good point, if you have questions like this, it's super helpful for you and others to work with a reproducible example. Just create the minimum amount of data and code to setup your question.

1 Like