Fred Boehm
Fred Boehm

Reputation: 668

rmarkdown inline code vs. code chunk

I'm working with an rmarkdown document in Rstudio, where I'm noticing some differences in the behavior of inline R code from R code in a code chunk. For instance, if I use the function lubridate::now() in a code chunk, I see that the time zone is appended to the output when I knit the Rmd document. However, when I use the same R code, i.e., lubridate::now(), as inline code and knit the document, I see that the time zone is not included in the output. Can you help me to understand this difference?

Thanks.

Upvotes: 3

Views: 4190

Answers (2)

Kevin
Kevin

Reputation: 339

For inline code the 'decoration' is removed so that you can use a computed value in a sentence. The chunks let you do a lot of processing, with or without displaying the outcome. If the code and the response are visible in the document, you can copy and paste it directly into the console and compare the outcomes.

Upvotes: 0

wibeasley
wibeasley

Reputation: 5287

Inline code passes through an additional layer --the "inline" hook. From the knitr manual:

  1. for each chunk, the code is evaluated using the evaluate package (Wickham, 2016), and the results may be filtered according to chunk options (e.g. echo=FALSE will remove the R source code) ...
  2. for normal texts, knitr will find inline R code (e.g. in \Sexpr{}) and evaluate it; the output is wrapped by the inline hook;

The inline hook can be examined by:

> knitr::knit_hooks$get("inline")
function (x) 
{
    if (is.numeric(x)) 
        x = round_digits(x)
    paste(as.character(x), collapse = ", ")
}
<environment: namespace:knitr>

If your rmd file is:

inline date: `r lubridate::now()`

```{r, echo=F}
lubridate::now()
print(lubridate::now())
paste(as.character(lubridate::now()), collapse = ", ")
```

The output is:

inline date: 2017-07-04 22:43:42

## [1] "2017-07-04 22:43:42 CDT"
## [1] "2017-07-04 22:43:42 CDT"
## [1] "2017-07-04 22:43:42"

Notice the inline output matches the third line of output from the chunk. This is my best guess anyway.

Upvotes: 7

Related Questions