6

How to do the following in org-mode:

  1. define a constant in the beginning of file, and
  2. than use it in the text or even compute on it.

Following methods didn't work for me:

Method 1:

#+CONSTANTS: t=10

The temperature is `$t`, and twice of that is `2*$t`.

How to do both of these?

Method 2:

The temperature is src_R{t=10; 2*t}, and twice of that is scr_R{4*t}.

Here value of t is defined in the first R code block (src_R{t=10; 2*t}), and the second block (scr_R{4*t}) is trying to compute on the definition of t. First block is replaced by 20 as expected, but the second block is not even interpreted as an R code. How can these two be connected?

  • 1
    Debug help: typo in 2nd inline block, scr_R should be src_R. – Melioratus Feb 1 '17 at 20:44
  • Thanks @Melioratus. That explains why the second block was not interpreted. – Shambho Feb 1 '17 at 23:56
6

Try this

  • Define t as default header argument with using :var t=10

    #+PROPERTY: header-args:R :var t=10
    
    The temperature is src_R{2*t}, and twice of that is src_R{4*t}.
    

    Note: Fixed typo in second in-line block and removed t=10; assignment.

    Exports as

    The temperature is `20', and twice of that is `40'.
    

Hope that helped!


Tested Using

emacs version: GNU Emacs 24.5.1
org-mode version: 9.0

  • Thanks again @Melioratus. This is exactly the kind of solution I was looking for. Much appreciated. – Shambho Feb 2 '17 at 0:02
5

You need to set the :session header argument. This tells org that all R calculations will take place in the same session. For example:

#+PROPERTY: header-args:R :session orgR

I set my constant here src_R{t=10; 2*t}.

Write some more text.

And reuse the constant here src_R{t * 4}.

On export, this generates:

enter image description here

4

I think the defined constant can be used in tables, and only there.

#+CONSTANTS: t=10

| 1 | 10 |
| 2 | 20 |
#+TBLFM: $2=$1*$t

However, you can add the header argument :session to make your second method working:

The temperature is src_R[:session]{t=10; 2*t}, and twice of that is src_R[:session]{4*t}.

You could also do a (not so pretty) trick. You could use a named table and assign that to a :var header argument:

#+name: t
| 10 |
#+TBLFM: $1=$t

The temperature is src_R[:var t=t]{t=10; 2*t}, and twice of that is src_R[:var t=t]{4*t}.
  • Thanks for the explanation @theldoria. This is very helpful. – Shambho Feb 2 '17 at 0:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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