# Selecting specific element from a list of lists based on values of another list

I have a list of pairs in which every pair correspond to a edge in a network (or graph). This list in a .txt file (available here https://drive.google.com/file/d/1g-1l3__IxJ8qe_wtM4_0TYuklwoH_Rqa/view?usp=sharing). What I have to do is select a random number of nodes in the network and then extract from the list above the edges that leave and arrive at each node i randomly selected. I managed to do this with the following code:

links = Import["<https://drive.google.com/file/d/1g-1l3__IxJ8qe_wtM4_0TYuklwoH_Rqa/view?usp=sharing>", "Data"];
randomNodes = RandomInteger[{firstNode, totalNodes}, 50];


Where I use the Max and Min functions to find the highest and lowest value attributed to a node in order to generate the list of randomly selected nodes using RandomInteger. Using the randomNodes list I have to find in the links list all the edges that go out from the node and also arrive at each of the nodes in randomNodes. The code below works fine for me:

selectedLinksOut =
Flatten[Table[
Select[links, #[[1]] == Sort[randomNodes][[i]] &], {i,
Length[randomNodes]}], 1];

Flatten[Table[
Select[links, #[[2]] == Sort[randomNodes][[i]] &], {i,
Length[randomNodes]}], 1];



But even for this set of data, which has about 25000 edges it takes a little bit to do this task. Would there be a way to do this maybe avoiding the use of Table to do it faster?

• can you make the file public?
– kglr
Jun 4, 2020 at 17:40
• My bad, I think it's public now Jun 4, 2020 at 17:42
• does List @@@ IncidenceList[UndirectedEdge @@@ links, Alternatives @@ randomNodes] give what you need?
– kglr
Jun 4, 2020 at 17:56
• .. or List @@@ EdgeList[UndirectedEdge @@@ links, UndirectedEdge[Alternatives @@ randomNodes, _]]?
– kglr
Jun 4, 2020 at 18:00
• Not exactly, this gives me a different output from finalLinks Jun 4, 2020 at 18:08

SeedRandom[1]
randomNodes = RandomInteger[{firstNode, totalNodes}, 50]


You can use Cases as follows:

lIn = Cases[{_, Alternatives @@ randomNodes}]@links;


True

lOut = Cases[{Alternatives @@ randomNodes, _}]@links;


True

lInOut = Union[lIn, lOut];


True


Alternatively,

lInOut2 = Cases[{Alternatives @@ randomNodes, _} | {_, Alternatives @@ randomNodes}]@

True