jangorecki jangorecki - 4 months ago 36
R Question

using .Last.value in rmarkdown/knitr

Having and Rmd file with below content:


It renders data.frame but rendering

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


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