2
$\begingroup$

I have an array that looks like M = {a, b, c, d}, where a, b, c, d are column vectors. I want to select rows from this array based on the elements in column c meeting a specified condition.

For example, if I have

M = {{"cat", 21, 10, 1}, {"dog", 7, 42, 2}, {"horse", 30, 1, 19},{"hippo", 99, 15,4}}

I want to take rows from this array based on the condition

c[[i]] >= 10

How could this be done? Ideally I would like to use Select as this can retrieve the sublist.

$\endgroup$
4
$\begingroup$

Feels like a duplicate of a bunch of questions, you could probably find by searching this forum... Some basic structures:

Select[M, #[[3]] >= 3 &]

{{"cat", 21, 10, 1}, {"dog", 7, 42, 2}, {"hippo", 99, 15, 4}}

Cases[M,x_/;x[[3]]>=3]

{{"cat",21,10,1},{"dog",7,42,2},{"hippo",99,15,4}}

$\endgroup$
3
$\begingroup$
Pick[M, UnitStep[M[[All, 3]] - 10], 1]

{{"cat", 21, 10, 1}, {"dog", 7, 42, 2}, {"hippo", 99, 15, 4}}

More general, you may use

check = # >= 10 &;
Pick[M, check /@ M[[All, 3]]]
$\endgroup$
  • $\begingroup$ Thanks Henrik; this technique wouldn't work if I exchange entries to arbitrary arrays, so is there perhaps a generalisation? I was thinking something like Select[M, (#[[All, 3]] >=10) &] - then (if it worked) the type of element wouldn't matter so much i.e. It could generalise to more complicated criteria $\endgroup$ – MKF Feb 6 at 22:26

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