1

How can I define vars in one org-babel code block and use them in a second? This closely follows the tutorial section block-to-block variable passing linked in the first answer.

# file test.org
* try a session.
#+name: section1
#+begin_src R :results output both :session
x <- c(1:10)
y <- x^2
mat <- cbind(x,y)
mat
#+end_src 

#this is outputted into the MWE after you press C-c C-c
#+RESULTS: section1
#+begin_example
       x   y
 [1,]  1   1
 [2,]  2   4
 [3,]  3   9
 [4,]  4  16
 [5,]  5  25
 [6,]  6  36
 [7,]  7  49
 [8,]  8  64
 [9,]  9  81
[10,] 10 100
#+end_example



#+name: section2
#+BEGIN_SRC R :file example2.png :results graphics mat=section1
plot(mat)
#+END_SRC

#this is outputted into the MWE after you press C-c C-c
#+RESULTS: section2
here is a white box with the phrase
object 'mat' not found
when it is named section 2 the white box appears in the first results 
#+begin_example section and the matrix of numbers disappears.
2

A standard feature of babel blocks is each block is executed in a new interpreter. Often this is good as changes in one block doesn't mess up others. I have two ideas for you...

In this particular case, you could break up the first block in two, so that the first block called the c function and spit out its results in a table that has the name, <named_block>. The other block would use that table output as a :var can call summary on it.

The third block would also set a :var and pass that to mean. That seems to me to be the most idiomatic approach. For details, see the Variables section in my Literate Programming tutorial.

Another approach is to set the :session parameter to some name, then each block that uses that same named session would share the same R interpreter, so setting variables in one block would then be accessible in the next. For details on this, see the Session section in the same tutorial.

Good luck.

1
* my.org

#+TITLE:TEST
#+AUTHOR:Benyomin
#+STARTUP: inlineimages

** This MWE graphs with a variable from an earlier code-block
#+begin_src R :results output :session
nums <- (seq(1,10))
nums
#+end_src

#+BEGIN_SRC R :file example.png :results graphics
plot(nums)
#+END_SRC

This is what happens after you hit C-c C-c both code blocks to execute the R code. MWE after code execution

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.