1
$\begingroup$

this is a basic question in Mathematica, I hope to get help to resolve it, How I can extract elements from matrics for example I have

list1 = {{"Dis", "S1", "S2", "S3", "S4", "S5", "S6"},
         {"D1", 1, 1, 0, 1, 1, 0}, {"D2", 1, 0, 1, 0, 0, 1}, {"D3", 0, 0, 1, 1, 0, 1},
         {"D4", 0, 1, 0, 0, 1, 1}, {"D5", 1, 1, 1, 0, 1, 1}, {"D6", 1, 1, 0, 0, 0, 1},
         {"D7", 0, 1, 1, 1, 0, 0}};
List2 = {{"Dis", "S7", "S8", "S4", "S9", "S10", "S3", "S11", "S12", "S5", "S1"},
         {"D2", 0, 1, 0, 0, 1, 0, 1, 1, 0, 0}, {"D8", 1, 1, 1, 1, 1, 0, 0, 0, 1, 0},
         {"D9", 1, 0, 1, 1, 0, 0, 0, 1, 0, 1}, {"D10", 0, 0, 1, 0, 0, 1, 1, 0, 0, 0},
         {"D6", 0, 1, 0, 0, 1, 0, 1, 0, 0, 1}, {"D11", 1, 1, 0, 1, 0, 1, 0, 1, 0, 1},
         {"D12", 0, 1, 0, 1, 0, 1, 0, 0, 0, 0}, {"D13", 1, 0, 1, 0, 1, 1, 0, 0, 0, 1},
         {"D14", 0, 1, 1, 1, 1, 0, 1, 1, 1, 1}, {"D15", 0, 1, 0, 0, 0, 0, 1, 0, 0, 0},
         {"D16", 0, 0, 0, 1, 0, 0, 0, 0, 1, 1}, {"D17", 1, 0, 1, 0, 0, 0, 1, 1, 0, 0}};

Imagine that D = represent Diseases the common diseases in between List 1 and List2 is

DL1 = Delete[List1[[All, 1]], {{1}}];
DL2 = Delete[List2[[All, 1]], {{1}}];
CommonD = Intersection[DL1, Dl2]
(* {D2, D6} *)

Does anybody have an idea can help me to extract all the element start with {"D2", "D6"} in order to obtain an output like this: from List1

{{"D2", 1, 0, 1, 0, 0, 1}, {"D6", 1, 1, 0, 0, 0, 1}}

Another list from List2

{{"D2", 0, 1, 0, 0, 1, 0, 1, 1, 0, 0}, {"D6", 0, 1, 0, 0, 1, 0, 1, 0, 0, 1}}

Anybody have any insight? Thanks!

$\endgroup$
1
  • $\begingroup$ Cases[list1, {"D1" | "D6", __}] and Cases[list2, {"D1" | "D6", __}] $\endgroup$
    – march
    Commented Apr 16, 2019 at 22:38

1 Answer 1

3
$\begingroup$

use something like

Flatten[(s=#;Select[list1,First@#==s&]),1]&/@{"D2","D6"}    

{{"D2", 1, 0, 1, 0, 0, 1}, {"D6", 1, 1, 0, 0, 0, 1}}

$\endgroup$
12
  • $\begingroup$ thank you so much, but if the '''CommonD//Dimension= 1000 not just two elements like above, output like that ={D2, D6, D3, Dn} $\endgroup$
    – Ben Aawf
    Commented Apr 17, 2019 at 9:27
  • $\begingroup$ this is not a problem.Just put commonD instead of {"D2","D6"} at the end of the code $\endgroup$
    – ZaMoC
    Commented Apr 17, 2019 at 9:31
  • $\begingroup$ I got output empty with error the out above{D2, D6} without double quote ,Flatten[(s = #; Select[List1, First@# == s &]), 1] & /@ {CommonD} $\endgroup$
    – Ben Aawf
    Commented Apr 17, 2019 at 9:43
  • 1
    $\begingroup$ Thanks J42161217 - that was incredibly helpful $\endgroup$
    – Ben Aawf
    Commented Apr 17, 2019 at 9:57
  • 1
    $\begingroup$ Thank you sooooo much $\endgroup$
    – Ben Aawf
    Commented Apr 17, 2019 at 10:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.