1
$\begingroup$

Suppose I have the matrix shown. Suppose I want the entire row data associated with specified column IDs 106, 110, 109. The output would be {106, Job2, J2},{110, Job7, J7},{109, Job5, J5}.

m = {{102, Job1, J1}, {106, Job2, J2}, {109, Job5, J5}, {110, Job7, 
   J7}, {120, Job9, J9}, {125, Job15, J15}}
MatrixForm[m]
$\endgroup$
2
$\begingroup$

Construct an Association with the first column as keys using GroupBy:

assoc =  GroupBy[m, First, First]

<|102 -> {102, Job1, J1}, 106 -> {106, Job2, J2}, 109 -> {109, Job5, J5}, 110 -> {110, Job7, J7}, 120 -> {120, Job9, J9}, 125 -> {125, Job15, J15}|>

You can extract the columns by mapping assoc

assoc /@ {106, 109, 110}

{{106, Job2, J2}, {109, Job5, J5}, {110, Job7, J7}}

or using Lookup:

Lookup[{106, 109, 110}] @ assoc

{{106, Job2, J2}, {109, Job5, J5}, {110, Job7, J7}}

$\endgroup$
  • $\begingroup$ very slick! ... thank you very much ... kglr $\endgroup$ – PRG May 28 at 16:57
2
$\begingroup$
index = Association[(#[[2]] -> #[[1]]) & /@ Table[{i, m[[i, 1]]}, {i, 1, Length[m]}]];
m[[index /@ {106, 110, 109}]]

{{106, Job2, J2}, {110, Job7, J7}, {109, Job5, J5}}

The strategy here is to use Association to make an index of the first column to the position of each ID in m. Then the association (index) can be used to extract the positions of arbitrary column IDs, which can be in turn used to extract the row information. This methodology retains the ordering of the query.

Otherwise, if ordering isn't important, Cases might be more useful for repeated evaluation:

Cases[m, {106 | 110 | 109, __}]

{{106, Job2, J2}, {109, Job5, J5}, {110, Job7, J7}}

Cases will also automatically de-duplicate repeated IDs, so keep that in mind if you go that route.

$\endgroup$
  • $\begingroup$ eyorble: very clever; wonderful and many thanks for your help! ... prg $\endgroup$ – PRG May 26 at 19:32
  • 1
    $\begingroup$ This preserves duplicates and ordering m // Select[MemberQ[{106, 110, 109}, First[#]] &] $\endgroup$ – Rohit Namjoshi May 27 at 0:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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