jangorecki jangorecki - 2 months ago 25
R Question

using .Last.value in rmarkdown/knitr

Having and Rmd file with below content:



```{r}
data.frame(a=1)
str(.Last.value)
```


It renders data.frame but rendering
str(.Last.value)
produces
## NULL
.

Is there any knitr option or a trick I can use to make it works as expected?

Expected output from the second

## 'data.frame': 1 obs. of 1 variable:
## $ a: num 1

Answer

Because all code chunks are evaluated via eval() in knitr, the last expression of a code chunk is not a top-level R expression, and .Last.value will not work for knitr.

To make this more clear:

x = 1
x  # a top-level expression if typed in the R console

By comparison, x is no longer a top-level expression in eval():

some_internal_knitr_function() {
  # internal code
  eval(parse(text = c('x = 1', 'x')))
  # more internal code
}