rmarkdown 内联代码与代码块

标签 r knitr r-markdown

我正在使用 Rstudio 中的 rmarkdown 文档,我注意到代码块中的内联 R 代码与 R 代码的行为存在一些差异。例如,如果我在代码块中使用函数 lubridate::now(),我会看到在编织 Rmd 文档时时区附加到输出中。但是,当我使用相同的 R 代码(即 lubridate::now())作为内联代码并编织文档时,我发现时区未包含在输出中。你能帮我理解这个区别吗?

谢谢。

最佳答案

内联代码通过一个附加层——“内联”钩子(Hook)。来自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;

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/

相关文章:

r - 在 R 中使用 httr POST 文件时指定文件名

r - 有条件地将一个向量乘以另一个 r

r - 将带有 Markdown 标签的 R 脚本作为外部文件包含在 Rmarkdown 文件中

RStudio knitr 主题

r - 使用结果 ='asis' 以编程方式插入 header 并使用 R markdown 在同一代码块中绘制

r - gam 包上的命名空间说明符不起作用

r - 将具有唯一值的列合并

r - 在发布到 Wordpress 时,在 KnitR 中包装 R 代码块以适应 html 的宽度

jquery - 删除数据表中的 'Show Entries'

R Markdown : levels of factor on different lines