9

It would be useful for me if I could write:

Grid[{{a, b}, {c, d}, {e, f}}, 
 GridHeadings -> {{"r1", "r2", "r3"}, {"c1", "c2"}}]

just like

TableForm[{{a, b}, {c, d}, {e, f}}, 
 TableHeadings -> {{"r1", "r2", "r3"}, {"c1", "c2"}}]

except that I don't want the two lines TableForm produces.

How could I add this additional option to Grid?

eldo
  • 67,911
  • 5
  • 60
  • 168

4 Answers4

3

I do not know of options that would do this to Grid. Grid is really just matrix with extra options build-in.

Can you just build-it in manually?

fillInHeader[h_, data_] := Module[{n, grid},
   n = Length[data];
   grid = Table[Null, {n + 1}, {n}];
   grid[[2 ;; -1, All]] = h[[1]];
   grid[[1, 2 ;; -1]] = h[[2]];
   grid[[2 ;; -1, 2 ;; -1]] = data;
   grid
   ];
headings = {{"r1", "r2", "r3"}, {"c1", "c2"}};
data = {{a, b}, {c, d}, {e, f}};
Grid[fillInHeader[headings, data]]

Mathematica graphics

If you want to add other Grid options, you can now do this

Grid[fillInHeader[headings, data], Frame -> All]

Mathematica graphics

You can use it with GraphicsGrid also

 GraphicsGrid[fillInHeader[headings, data], ImageSize -> 100]

Mathematica graphics

etc...

Nasser
  • 143,286
  • 11
  • 154
  • 359
  • using your code above: why shouldn't it be posssible to unprotect "Grid" and add it as an option? – eldo Jun 03 '14 at 06:16
  • @eldo, I would not know how to do this. I also think making a simple function to fill-in the headers on the sides of the data is just simpler than what you suggest. – Nasser Jun 03 '14 at 06:19
3
data = {{a, b}, {c, d}, {e, f}};
headings = {{"r1", "r2", "r3"}, {"c1", "c2"}};

Grid[Prepend[Flatten /@ Transpose[{headings[[1]], data}], 
             PadLeft[headings[[2]], Length@data[[1]] + 1, ""]]]

enter image description here

I assume data sublists of same length, if not the case, more work needed as this (and other answers so far) will give goofy results.

ciao
  • 25,774
  • 2
  • 58
  • 139
3
data = {{a, b}, {c, d}, {e, f}};
head = {{"r1", "r2", "r3"}, {"c1", "c2"}};


Join[Transpose[{Join[{""}, head[[1]]]}], Join[head[[{2}]], data], 2] // Grid

enter image description here

Kuba
  • 136,707
  • 13
  • 279
  • 740
  • I am very pleased. "MyGrid[d_, h_] := Join[Transpose[{Join[{""}, h[[1]]]}], Join[h[[2]], d], 2] // Grid" now easily gives me what I wanted. Just flipped an acceptance coin between rasher and you. – eldo Jun 03 '14 at 07:26
  • 3
    @eldo: In the future, please use Mathematica's RandomInteger for such decisions: I've seen coins with Kuba's face on both sides... ;-) – ciao Jun 03 '14 at 07:32
1

Here's another idea that makes use of ArrayFlatten

 GridPlus[data_, headers_, opts : OptionsPattern[Grid]] := 
 Grid[ArrayFlatten[{{{{""}}, {headers[[1]]}}, \
 {Transpose[{headers[[2]]}], data}}], opts]
Seth Chandler
  • 3,132
  • 14
  • 25