10

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?

Dan
  • 32,584
  • 6
  • 98
  • 168
Shambho
  • 457
  • 3
  • 13

3 Answers3

7

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

Melioratus
  • 4,504
  • 1
  • 25
  • 43
  • Thanks again @Melioratus. This is exactly the kind of solution I was looking for. Much appreciated. – Shambho Feb 02 '17 at 00: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

Tyler
  • 21,719
  • 1
  • 52
  • 92
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}.
theldoria
  • 1,825
  • 1
  • 13
  • 25