4
$\begingroup$

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"?

$\endgroup$

6 Answers 6

6
$\begingroup$

If you transpose your data you can use "Cases" like:

Cases[Transpose[tabtest], {"a", __}] // Transpose // MatrixForm

enter image description here

$\endgroup$
11
$\begingroup$

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}}
*)
$\endgroup$
5
$\begingroup$
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}
   } *) 
$\endgroup$
5
$\begingroup$
Extract[Position[tabtest[[1]], "a"]] /@ tabtest

or

Select[Transpose[tabtest], First/*EqualTo["a"]] // Transpose
$\endgroup$
3
$\begingroup$
dt = MapApply[#1 -> {##2} &] @ Transpose[tabtest];

Lookup[#, "a", Nothing] & /@ dt // Transpose // MatrixForm

enter image description here

$\endgroup$
2
$\begingroup$

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

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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