我正在使用 Rstudio 中的 rmarkdown 文档,我注意到代码块中的内联 R 代码与 R 代码的行为存在一些差异。例如,如果我在代码块中使用函数 lubridate::now()
,我会看到在编织 Rmd 文档时时区附加到输出中。但是,当我使用相同的 R 代码(即 lubridate::now()
)作为内联代码并编织文档时,我发现时区未包含在输出中。你能帮我理解这个区别吗?
谢谢。
最佳答案
内联代码通过一个附加层——“内联”钩子(Hook)。来自knitr manual :
- 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) ...
- for normal texts, knitr will find inline R code (e.g. in \Sexpr{}) and evaluate it; the output is wrapped by the inline hook;
inline hook可以通过以下方式检查:
> knitr::knit_hooks$get("inline")
function (x)
{
if (is.numeric(x))
x = round_digits(x)
paste(as.character(x), collapse = ", ")
}
<environment: namespace:knitr>
如果您的 rmd 文件是:
inline date: `r lubridate::now()`
```{r, echo=F}
lubridate::now()
print(lubridate::now())
paste(as.character(lubridate::now()), collapse = ", ")
```
输出是:
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"
注意内联输出与 block 输出的第三行相匹配。无论如何,这是我最好的猜测。
关于rmarkdown 内联代码与代码块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44910539/