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.

3
  • and you don't want to use #+tblflm: @3$2 = vsum (@I..II) is that correct? Commented Jun 23, 2018 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
    Commented Jun 24, 2018 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
    Commented Jun 24, 2018 at 6:35

1 Answer 1

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

5
  • 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
    Commented Jun 24, 2018 at 6:40
  • I’ll take a look and see if I can fix that.
    – Melioratus
    Commented Jun 24, 2018 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
    Commented Jun 24, 2018 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
    Commented Jun 25, 2018 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
    Commented Jun 25, 2018 at 17:34

Your Answer

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

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