# Pull the data from a set of chosen rows of a table

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]


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}}

• very slick! ... thank you very much ... kglr May 28, 2019 at 16:57
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.

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

Lookup also works with Lists of Rules:

look = MapApply[# -> {##} &] @ m;


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

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


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

To omit the Keys:

look = MapApply[#1 -> {##2} &] @ m;

Lookup[110] @ look


{Job7, J7}

Construct an association using Association as follows:

assoc = Merge[Association[# -> {##}] & @@@ m, Catenate]


You can extract the columns using Extract:

Values@Extract[assoc, List /@ {Key /@ {106, 109, 110}}][[1]]

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