2

Let's say I have the following org-tables:

| col1 | col2 |
|    1 | 2    |
| col3 |
| 3    |

What's the easiest programmatic way to get the following output:

| col1 | col2 | col3 |
|    1 |    2 | 3    |
  • Manually or programmatically? – choroba Mar 21 at 15:36
  • Programmatically. – андрэ Mar 21 at 15:47
7

You can use cl-mapcar.

#+NAME: T1
| col1 | col2 |
|    1 | 2    |

#+NAME: T2
| col3 |
| 3    |

#+BEGIN_SRC emacs-lisp :var t1=T1 t2=T2
(cl-mapcar #'append t1 t2)
#+END_SRC

#+RESULTS:
| col1 | col2 | col3 |
|    1 |    2 |    3 |

A nice side-effect of that solution is that it does not hurt if one table stops early. The resulting table is just as long as the shortest input table.

#+NAME: T1
| col1 | col2 |
|   11 |   12 |
|   21 |   22 |
|   31 |   32 |

#+NAME: T2
| col3 |
|   13 |
|   12 |

#+BEGIN_SRC emacs-lisp :var t1=T1 t2=T2 :colnames no
(cl-mapcar #'append t1 t2)
#+END_SRC

#+RESULTS:
| col1 | col2 | col3 |
|   11 |   12 |   13 |
|   21 |   22 |   12 |

If you have actually headers you can use:

#+NAME: T1
| col1 | col2 |
|------+------|
|    1 |    2 |

#+NAME: T2
| col3 |
|------|
|    3 |

#+BEGIN_SRC emacs-lisp :var t1=T1 t2=T2 :colnames no
(insert-at 1 (cl-mapcar #'append t1 t2) 'hline)
#+END_SRC

#+RESULTS:
| col1 | col2 | col3 |
|------+------+------|
|    1 |    2 |    3 |

Thereby, insert-at is defined by:

(defun insert-at (n list element)
  "Insert ELEMENT into LIST at position N.
I.e., (eq ELEMENT (nth N (insert-at N LIST ELEMENT)))."
  (if (eq n 0)
      (cons element list)
    (let ((link (nthcdr (1- n) list)))
      (setcdr link (cons element (cdr link))))
    list))
  • That's... lovely! – андрэ Mar 21 at 16:39
  • 1
    Uups the definition of insert-at is from my own lisp library. I'll replace it with something standard in a moment... – Tobias Mar 21 at 16:53

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .