67

In R markdown (knitr package), can I access a variable within the body of the document that was calculated in a code chunk?

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
m.templemire
  • 725
  • 1
  • 6
  • 8

3 Answers3

104

Yes. You can simply call any previously evaluated variable inline.

e.g. If you had previously created a data.frame in a chunk with df <- data.frame(x=1:10)

`r max(df$x)`

Should produce

10
Maiasaura
  • 32,226
  • 27
  • 104
  • 108
  • 17
    But do note that that will be typeset as code which may not be what is wanted if you wish to use it in plain text. `r I(max(df$x))` should work as well and not typeset in code format. – Gavin Simpson Jun 05 '12 at 19:36
17

You can acces to variable previously created so

`r variable`

But if the variable is numeric and you want add to a pdf document, you should convert variable in string so

`r toString(variable)`
7

I would like to add that this is not the case for other languages than R. I know the question is solved and about R, but maybe someone else finds this useful:

Except engine='R' (default), all chunks are executed in separate sessions, so the variables cannot be directly shared. If we want to make use of objects created in previous chunks, we usually have to write them to files (as side effects). For the bash engine, we can use Sys.setenv() to export variables from R to bash (example). Another approach is to use the (experimental) runr package.

Source

Example in R:

x = 4

print(x)

## [1] 4

Python Example 2a):

x=1
print(x)

## 1

Python Example 2b):

print(x)

## Traceback (most recent call last):
##   File "<string>", line 1, in <module>
## NameError: name 'x' is not defined

Just FYI.

inktrap
  • 370
  • 3
  • 11
  • 1
    My current experience is that they've improved this, and now objects persist across Python chunks. – David Kaufman Jan 31 '20 at 23:43
  • 4
    @david-kaufman, agreed. Just ran across this page after finding this quote in the documentation: "Currently the only exceptions are `r`, `python`, and `julia`. Only these engines execute code in the same session throughout the document." Source: https://bookdown.org/yihui/rmarkdown/language-engines.html – D. Woods Feb 03 '20 at 18:14