2
$\begingroup$

Suppose I have the following edge list

edges = {N1003 -> N1003, N1003 -> N1099, N8911 -> N23122, N34019 -> N36051, N1019 -> N36001, N36019 -> N36043, N3405 -> N3423, N36291 -> N36004} 

I've tried various string argument to no avail. I'd like to extract just the edges in the above edgelist that contains the string N34 and N36. For example, I'm looking to just extract what would be the last 5 edges in the above edge list. The last 5 edges contain an N34 or an N36 in one end or both ends of the "a->"b" pair. Thoughts? Many thanks.

I've tried this ... it works ... but it is not efficient ...

Flatten[List[ Select[edges, And @@ {StringContainsQ[ToString@#[[1]], ""], StringContainsQ[ToString@#[[2]], "N36"]} &], Select[edges, And @@ {StringContainsQ[ToString@#[[1]], ""], StringContainsQ[ToString@#[[2]], "N34"]} &], Select[edges, And @@ {StringContainsQ[ToString@#[[1]], "34"], StringContainsQ[ToString@#[[2]], ""]} &], Select[edges, And @@ {StringContainsQ[ToString@#[[1]], "36"], StringContainsQ[ToString@#[[2]], ""]} &]]] 
$\endgroup$
2
  • 1
    $\begingroup$ Those are not actually strings. Are they supposed to be strings? $\endgroup$ Commented Sep 15, 2023 at 19:55
  • $\begingroup$ No they don't have to be strings $\endgroup$ Commented Sep 15, 2023 at 20:06

2 Answers 2

4
$\begingroup$

Here is one way.

edges = {N1003 -> N1003, N1003 -> N1099, N8911 -> N23122, N34019 -> N36051, N1019 -> N36001, N36019 -> N36043, N3405 -> N3423, N36291 -> N36004} 

Turn whole edges into strings:

edges2 = ToString /@ edges; 

Find ones with "N34" or "N36" then convert back to expressions:

ToExpression@Select[edges2, StringContainsQ[#, {"N34", "N36"}] &] 

{N34019 -> N36051, N1019 -> N36001, N36019 -> N36043, N3405 -> N3423, N36291 -> N36004}

$\endgroup$
3
$\begingroup$
pred = Apply[Or] @* StringStartsQ["N34"|"N36"] @* Map[SymbolName] @* Apply[List]; 

1.

Use pred with Select:

Select[pred] @ edges 

enter image description here

2.

Use pred with EdgeList:

EdgeList[edges, _?pred] 

enter image description here

$\endgroup$
1
  • 4
    $\begingroup$ MelaGo and kglr: These are both wonderfully efficient answers compared to mine ... thank u both very much ... I always learn from these correspondences and thank u for sharing your talents ... $\endgroup$ Commented Sep 15, 2023 at 21:17

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.