Search code examples
remacsorg-modeorg-table

org-mode: add a header to a table programmatically


I have a table defined in org-mode:

#+RESULTS[4fc5d440d2954e8355d32d8004cab567f9918a64]: table
|  7.4159 | 3.0522 |  5.9452 |
| -1.0548 | 12.574 | -6.5001 |
|  7.4159 | 3.0522 |  5.9452 |
|  5.1884 | 4.9813 |  4.9813 |

and I want to produce the following table:

#+caption: Caption of my table
|        | group 1 | group 2 | group 3 |
|--------+---------+---------+---------|
| plan 1 |   7.416 |   3.052 |   5.945 |
| plan 2 |  -1.055 |  12.574 |    -6.5 |
| plan 3 |   7.416 |   3.052 |   5.945 |
| plan 4 |  5.1884 |  4.9813 |  4.9813 |

How can I accomplish that? Here is what I tried (in R):

#+begin_src R :colnames yes :var table=table :session  
data.frame(table)
#+end_src

But of course it doesn't work, here is what I get:

#RESULTS:
| X7.4159 | X3.0522 | X5.9452 |
|---------+---------+---------|
| -1.0548 |  12.574 | -6.5001 |
|  7.4159 |  3.0522 |  5.9452 |
|  5.1884 |  4.9813 |  4.9813 |

Any suggestions?

thanks!


Solution

  • This gets pretty close. first define this function:

    #+BEGIN_SRC emacs-lisp
    (defun add-caption (caption)
      (concat (format "org\n#+caption: %s" caption)))
    #+END_SRC
    

    Next, use this kind of src block. I use python, but it should work in R too, you just need the :wrap. I passed your data in through the var, you don't need it if you generate the data in the block.

    #+BEGIN_SRC python :results value :var data=data :wrap (add-caption "Some really long, uninteresting, caption about data that is in this table.")
    data.insert(0, ["", "group 1", "group 2", "group 3"])
    data.insert(1, None)
    return data
    #+END_SRC
    

    This outputs

    #+BEGIN_org
    #+caption: Some really long, uninteresting, caption about data that is in this    table.
    |        | group 1 | group 2 | group 3 |
    |--------+---------+---------+---------|
    | plan 1 |   7.416 |   3.052 |   5.945 |
    | plan 2 |  -1.055 |  12.574 |    -6.5 |
    | plan 3 |   7.416 |   3.052 |   5.945 |
    | plan 4 |  5.1884 |  4.9813 |  4.9813 |
    #+END_org
    

    and it exports ok too I think.