Consider the following table:
tabtest =
Join[{{"a", "a", "b", "c", "c", "c", "d", "e"}},
RandomReal[{1, 2}, {10, 8}]]
Could you please tell me how to leave extract only the columns starting with, say, "a"
?
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityIf you transpose your data you can use "Cases" like:
Cases[Transpose[tabtest], {"a", __}] // Transpose // MatrixForm
Perhaps this:
SeedRandom[0];
tabtest =
Join[{{"a", "a", "b", "c", "c", "c", "d", "e"}},
RandomReal[{1, 2}, {10, 8}]];
tabtest[[All, Flatten@Position[First@tabtest, "a", 1]]]
(*
{{"a", "a"}, {1.65247, 1.63307}, {1.1011, 1.64552}, {1.87669,
1.01913}, {1.28242, 1.29648}, {1.43271, 1.12359}, {1.95713,
1.63538}, {1.02266, 1.16359}, {1.09437, 1.79686}, {1.746,
1.49077}, {1.44829, 1.44897}}
*)
tabtest[[All,PositionIndex[First@tabtest]["a"]]]
(* {
{a,a},
{1.1943,1.28724},
{1.78077,1.23776},
{1.86472,1.81003},
{1.41396,1.81898},
{1.32723,1.97021},
{1.66714,1.79951},
{1.15126,1.05214},
{1.95384,1.30154},
{1.61523,1.98808},
{1.65683,1.50416}
} *)
Extract[Position[tabtest[[1]], "a"]] /@ tabtest
or
Select[Transpose[tabtest], First/*EqualTo["a"]] // Transpose
dt = MapApply[#1 -> {##2} &] @ Transpose[tabtest];
Lookup[#, "a", Nothing] & /@ dt // Transpose // MatrixForm
Another method using Tally
:
f[tab_, lab_] :=
If[MemberQ[Last /@ Position[tab, lab], 1] === False,
Transpose@(Rest @@ (Most@*Transpose@Tally[Transpose@tab, FreeQ[{#1, #2}, lab] &])),
Transpose@(Most @@ (Most@*Transpose@Tally[Transpose@tab, FreeQ[{#1, #2}, lab] &]))]
Example:
f[tabtest, "a"] // MatrixForm