Calculate number of common neighbors in igraph R - r

Can anyone help me to find the number of common neighbors of two vertices using igraph R.
I tried to get this with following command but it returned with list().
intersect(neighborhood(graph=TD1,order=1,nodes=714),neighborhood(graph=TD1,order=1,nodes=4211))
>>>> list()
Thanks
Anna

neighborhood() returns a list of integer vectors, one for each source node you passed in. Since you only have a single source node, you have to extract the first element of the list that neighborhood() returns before passing them to intersect():
intersect(
neighborhood(graph=TD1, order=1, nodes=714)[[1]],
neighborhood(graph=TD1, order=1, nodes=4211)[[1]]
)

Related

Export path sequence of all shortest path in a network

I have two networks in igraph where I'd like to extract the path sequences (not just the length) of all shortest path from the first network in the second one.
The idea behind that is:
I have stored the information of an origin-destination dataframe in net2.
So I have the start and end node of trips. What I don't have is the nodes visited between start and end node.
I assume that the agents will choose the shortest_path for traveling.
In net (first network) I have a whole network with nodes and edges attributed with travel times.
Now I would like to see how the agents in the origin-destination dataframe (net2) travel from the start to the end node while choosing shortest paths.
This means: I need to combine both networks. One has the information of the origin-destination relation,the other has the sequence of connecting nodes. Or in other words: Which vertices use the agents from net2 in net to get to their desired node.
To get the shortest path sequence of my network net I used igraph::shortest_paths.
This gives me an igraph.vs object with the desired information.
Now I would like to store this information in dataframe but I don't know how to access it.
I tried:
df<-unlist(shortest_paths(net,from =od$from,to=od$to)
where od is the origin-destination df
Now I want to store the multidimensional list as a dataframe.
results <- unlist(df, recursive = F)
results <- sapply(results, as_ids)
result_df <- as.data.frame(matrix(results))
When I'm doing this I get the error:
Error in UseMethod("as_ids") :
no applicable method for 'as_ids' applied to an object of class "c('integer', 'numeric')"
I don't know if it's a misspell or you are using a different version, but I can't find the shortest_path() function, only the one you have mentioned later: shortest_paths().
If I understand clearly, you want to extract the exact shortest path sequences in a list of vertices (list of lists containing vertices), and convert it to a DF.
Here's my solution:
library('igraph')
set.seed(24)
g <- as.undirected(barabasi.game(20, power = 0.5, m = 4))
results <- sapply(V(g), function(x){ all_shortest_paths(g, from = x, to = V(g)[-x])$res})
results <- unlist(results, recursive = F)
results <- sapply(results, as_ids)
result_df <- as.data.frame(matrix(results))
I extracted the shortest paths by calling the all_short all_shortest_paths on each vertex, where the from parameter is the current vertex, and the to parameter is the list of the other vertices, minus the current one. Only the res attribute is needed from the given structure.
This gave me a multidimensional list: lists of vertex lists (every shortest path from the given vertex) for every node.
...
[[15]]
[[15]][[1]]
+ 3/20 vertices, from 84297ee:
[1] 15 14 1
[[15]][[2]]
+ 3/20 vertices, from 84297ee:
[1] 15 7 1
[[15]][[3]]
+ 3/20 vertices, from 84297ee:
[1] 15 5 1
[[15]][[4]]
+ 3/20 vertices, from 84297ee:
[1] 15 8 2
...
Once I have unlisted one layer of it, I got the inner list of vertices. This is an igraph.vs structure, and you have to convert it with the sapply(,as_ids) function as it is mentioned here.
After this step, you can work further with your simple list of vertex name lists, converting them to a data.frame
I converted my o-d-matrix to a graph as I assume this will run faster.
I still get the error: Error in UseMethod("as_ids") :
no applicable method for 'as_ids' applied to an object of class "c('integer', 'numeric')"
Might this be due to the class of my edgelist? I have vertices with IDs like: U1309?
When I call str(links) it is a character. Do I need to convert the class of my edgelist? Or is there another command to turn the vertex sequence into an ordninary vector?

R combine two lists of sfc_polygons

Hej,
I have two lists of polygons.
The first one is a list of 1 polygon (circle)
The second is a list of 260 polygons (260 rectangles).
See the first picture (two lists of polygons).
Now I want to keep all the rectangles that are touched by the circle.
See picture 2 merge and 3 result.
Does somebody has any idea? There are serveral things. st_combine, st_intersection - but their are not useable for this problem.
Suppose your blocks are in a, and your circle in b; have you tried
a[lenghts(st_intersects(a, b)) > 0]
?
Without a reprex it's hard to give a full answer, but I think you want to use st_intersects. This can take two sf objects and return either a list of vectors of pairs that intersect (sparse = TRUE) or a full logical matrix of whether those indices intersect (sparse = FALSE). In this case, I would use the latter, and then appropriate filter to get only the rows you want.

Connect dots function

I am learning cross validation method.
In the lines below, the input and query are both a data frame.
my.knn <- get.knnx(input,query,k=2)
nn.index <- my.knn$nn.index
What does the second line mean? What will nn.index be?
my.knn is a list of variables. So nn.index is taking that value out of the list so you can work on it as a single variable.
EXAMPLE OF GETTING ELEMENTS OUT OF A LIST
stats <- list("mean" = 10, "data" = c(0, 10 ,20))
#just get the average out
my.average <- stats$mean
So a list can have different kind of results from your testing, and can have a mix of variable types (integers, strings, vectors). The $ syntax is taking one of the variables out of the list into a single variable.
If you type my.knn at the prompt you will see its contents with sections marked with $. This will help see what is in your list.
In the example:
> stats
$mean
[1] 10
$data
[1] 0 10 20
SPECIFICS ON FUNCTION
I looked at get.knnx function notes, assuming you are using FNN package, here http://www.inside-r.org/packages/cran/fnn/docs/get.knn:
Output a list contains:
nn.index
an n x k matrix for the nearest neighbor indice(s).
nn.dist
an n x k matrix for the nearest neighbor Euclidean distances.
So you can see your function output list has these two variables - an index of the nearest neighbour, and the second is the distances.
Trust this helps.

Get a vertex in a vertex sequence

A vertex sequence by igraph seems not be a sequence. For example:
The v sequence by V( module.net ) is a sequence, since I can access it by [deg==1]. But why it does't work when I try peripheral[1]? Any possible explanation for this?
The dataset for this example is not easy to be included, sorry for that.
//
I find the answer, the index of first vertex 'MED24' is 4, instead of 1. So if I want to get the first vertex, I have to do peripheral[1]. But this seems a little unreasonable. A replicatable example:
g = graph.ring(5)
V(g)$name = c('node1', 'node2', 'node3','node4','node5')
temp = V(g)[2:3]
If you want to access 'node3' from temp, you have to use temp[3] instead of temp[2]
I've always had trouble with vertex sequences and edge sequences. The problem with the indexing operator on those objects is that is searched by vector name, not position. So peripheral[1] is looking to see if vector 1 is in the list, it's not extracting the first element in the list.
The best i've come up with is converting the sequence to a simple vector and re-indexing the vector list. For example
el <- cbind(letters[1:5], letters[c(2,3,5,1,4)])
gg <- graph.edgelist(el)
p <- V(gg)[c(2,3)]
V(gg)[as.vector(p)[1]]
Actually, if you just want to extract the name of a particular vertex, then
p$name[1]
would work.

Getting elements of a list in R

This is my problem:
There is a predefined list named gamma with three entries: gamma$'2' is 2x2 matrix gamma$'3' a 3x3 matrix and gamma$'4' a 4x4 matrix. I would like to have function that returns the matrix I need:
GiveMatrix <- function(n) {
gamma.list <- #init the list of matrices
gamma.list$n # return the list entry named n
Since n is not a character, the last line does not work. I tried gamma.list$paste(n)and gamma.list$as.character(n)but both did not work. Is there a function that converts nto the right format? Or is there maybe a much better way? I know, I am not really good in R.
You need to use:
gamma.list[[as.character(n)]]
In your example, R is looking for a entry in the list called n. When using [[, the contents of n is used, which is what you need.
I've found it!
gamma.list[as.character(n)] is the solution I needed.

Resources