1
$\begingroup$

I have a dataset, where each element in the list is a vector as in

data = Table[{i, 2 i, 3 i}, {i, 1, 10}]

As an example, I am interested in the entries where the last vector-element is greater than 6. The page in the Documentation Center only goes through the 1-dimensional case - is there a way to generalize to a vector-case?

One alternative would be to use a For-loop, but computationally I think that is less efficient than Select.

$\endgroup$
  • 5
    $\begingroup$ There are many ways, e.g. Select[Table[{i, 2 i, 3 i}, {i, 1, 10}], #[[3]] > 6 &]. This has been asked many times, so you may find more answers if you look a bit at this site. $\endgroup$ – Artes Jul 28 '13 at 12:47
  • $\begingroup$ You can also use Cases: Cases[data,{,,x_}/;x>6] $\endgroup$ – mgm Jul 28 '13 at 13:14
  • $\begingroup$ This would be faster, Pick[#, 1 - UnitStep[6 - #[[All, 3]]], 1] &@Table[{i, 2 i, 3 i}, {i, 1, 10}] $\endgroup$ – chyanog Jul 28 '13 at 13:21
3
$\begingroup$

There is one way:

data = Table[{i, 2 i, 3 i}, {i, 1, 10}];
Select[data, #[[-1]] > 6 &]

{{3,6,9},{4,8,12},{5,10,15},{6,12,18},{7,14,21},{8,16,24},{9,18,27},{10,20,30}}

And another form is:

Cases[data, x_ /; x[[-1]] > 6, {1}]

And:

Cases[data, x_?(#[[-1]] > 6 &), {1}]

All with similar performace. I prefer Select.

|improve this answer|||||
$\endgroup$
  • $\begingroup$ I would make this even more general by defining makeTest[index_Integer, cutOff_?NumericQ] := #1[[index]] > cutOff &, which can be used, for example, as Select[data, makeTest[3, 6]] or Select[data, makeTest[-1, 6]] to solve the OP's example problem, but also allows selecting for any cutoff point as well as any column in the data points. $\endgroup$ – m_goldberg Jul 28 '13 at 15:28

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