1

I want to (non-interactively) add (one hline and) a last line to a table in which the last column is summed.

Like so:

#+name: mytable
| p | q |
|---+---|
| a | 5 | 
| b | 2 |


#+begin_src emacs-lisp :var table=mytable
  (append table ?)
#+end_src

#+RESULTS:
| p | q |
|---+---|
| a | 5 | 
| b | 2 |
|---+---|
|   | 7 |

I suspect org-table-sum can help, but I am unsure how.

  • and you don't want to use #+tblflm: @3$2 = vsum (@I..II) is that correct? – manandearth Jun 23 '18 at 18:58
  • 1
    Thanks for your question! You may want to update the title of your question to clarify what is required. Perhaps something like, How to add hline and column sum to bottom of table using a src block?. This change will help your question standout against the common vsum is the answer questions. – Melioratus Jun 24 '18 at 0:45
  • That is correct, @manandearth. I want to be able to do it non-interactively (as part of a babel block's :post function, to be exact). – Werner Jun 24 '18 at 6:35
3

Try this

#+name: mytable
| p | q |
|---+---|
| a | 5 |
| b | 2 |
| c | 3 |


#+begin_src emacs-lisp :var table=mytable :colnames yes 
  (let* ((total (apply '+ (mapcar 'car (mapcar 'cdr table))))  )
    (append table `(hline ("" ,total))))
#+end_src

#+RESULTS:
| p |  q |
|---+----|
| a |  5 |
| b |  2 |
| c |  3 |
|---+----|
|   | 10 |

Tip: To keep column names add :colnames yes to code block headers.


This code was tested using:
emacs version: GNU Emacs 25.2.1 (x86_64-unknown-cygwin, GTK+ Version 3.22.10)
Org mode version: 9.1.2

  • Great! This eats a potential existing header and its hline, though (which I did not add to my example table in the question). Not sure where in your code the car and hline get lost as all you seem to be doing is appending something. – Werner Jun 24 '18 at 6:40
  • I’ll take a look and see if I can fix that. – Melioratus Jun 24 '18 at 14:17
  • 1
    @Werner - I added :colnames yes to the headers of the code block which fixed the issue. Hope that helped! Thanks for asking your question! – Melioratus Jun 24 '18 at 14:37
  • For posterity (and the general robustness of your answer) it might be useful to ensure that the last column is added (as this strikes me as far more common), instead of the second. Would you agree? – Werner Jun 25 '18 at 6:51
  • @Werner - Good point! Thanks for the recommendation! I'm still learning elisp and several other lispy languages. I've read about a last function(?)/macro(?) but I can't remember which language. I'll read up, do some tests. and make the update to the answer. – Melioratus Jun 25 '18 at 17:34

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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