How to find the neighborhood for certain vertices only?

北城余情 提交于 2019-12-11 04:57:19

问题


The question was started here.

I have an undirected graph g with n<100 vertices. The graph is simple. The coordinates of all vertices are integer (x_i, y_i), i=1, 2,..., n, the set of edges is predefinded, they are line segments with the length 1 unit. The degree of vertices can be 2, 3 or 4.

library(igraph)

g <- graph_from_literal(1-2-3-4-5-6-7-8-1, 8-9-4)
B <- t(matrix(c(0,0, 0,1, 0,2, -1,2, -2,2, -2,1, -2,0, -1,0, -1,1), nrow =2));

V(g)$id <- seq_len(vcount(g))

V(g)$x <- B[,1]; V(g)$y <- B[,2]

plot(g, layout=as.matrix(B))

I need to set the new attribute for vertex the corner attribute.

We say the vertex i is the corner vertex if its degree is 2 and two incident edges do not lie on the same line. On the plot above vertices 1, 3, 5, 7 are corner vertices while remaining vertices 2, 4, 6, 8, 9 are non-corner.

My attempt

I have found the list of vertices that have degree equal to 2.

idv <- V(g)[strength(g)==2]; idv # 1 2 3 5 6 7 9

Then the list of neighborhood vertices for i-th vertex was found.

neigh<-neighborhood(g, idv); neigh

The error is here, because I see the neighborhood vertices for all vertices, no only vertices that have degree equal to 2. For instance,

neigh[[4]]; neigh[[8]];   
#[1] 4 3 5 9
#[1] 8 1 7 9

Question. How to use the neighborhood function to find the neighborhood for vertices with degree 2 only?


回答1:


The function is correct, but the second argument isn't about vertices of interest, it's the third one:

neighborhood
# function (graph, order = 1, nodes = V(graph), mode = c("all", 
#     "out", "in"), mindist = 0) 
# {
# ...

Thus,

length(neighborhood(g, nodes = idv))
# [1] 7

does the job.



来源:https://stackoverflow.com/questions/56392883/how-to-find-the-neighborhood-for-certain-vertices-only

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!