如何解释 Rmarkdown 中的复杂函数? [英] How do I explain a complicated function in Rmarkdown?

查看:57
本文介绍了如何解释 Rmarkdown 中的复杂函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有点复杂的 R 函数(不同的部分指的是我想解释的各种方程.)我想使用 R Markdown 编写我的代码,但我需要能够在文档中解释函数的不同部分.有点像文学编程.

I have a somewhat complicated R function (different parts refer to various equations I'd like to explain.) I want to write my code using R Markdown, but I need to be able to explain the different parts of the function in the document. A bit like literate programming.

我想知道是否可以将函数定义拆分到不同的代码块中,或者在函数定义中插入降价注释?

I wonder if it is possible to split the function definition across different code chunks, or maybe insert markdown comments inside the function definition?

我希望最终结果看起来像这样:

I'd like the end result to look something like this:

complicated = function(x) {

我在示例中使用了 x^2,所以它是数学式的,而且很简短.这是实际的 R 代码:

I use x^2 in the example so it is math, and yet short. Here it is in the actual R code:

  x^2
}

这不起作用:

``` {r}
complicated = function(x) {
```
explain the function with some math $x^$.
``` {r}
 x^2
}
```

以下实际上确实有效:

``` {r chunk1, echo=FALSE}
complicated=function(x) {
  x^2
}
```

``` {r chunk1, echo=1:2, eval=F}
```
In the complicated function I use x^2 as an example.

虽然有点棘手,因为如果函数中的行发生变化,我必须再次编辑所有内容.同样在 Rmd 文件中,您实际上看不到注释所描述的代码.

Though it is a bit tricky, because if lines in the function change, I have to edit everything again. Also in the Rmd file, you don't actually see the code described by the comments.

也许有可能以某种方式将相关块写入文件而不进行评估,然后文件读入?我还没想出办法...

Maybe it is possible to somehow have the relevant chunks written to a file without being evaluated, and then the file read in? I didn't manage to figure out a way yet...

推荐答案

我找到了一个很好的答案,尽管它看起来有点像 knitr 错误.我希望它不会被修复.事实证明,在 Rmd 中对块的引用就像在 Rnw 中一样.你只需要使用 <<> 来引用一个块.

I found a nice answer to this question, though it looks a bit like a knitr bug. I hope it doesn't get fixed. It turns out that references to chunks work in Rmd just like in Rnw. You just have to use <<chunk name>> to refer back to a chunk.

所以,这是答案:

```{r Xsquare, eval=F}
x^2
```
We just need to take x and raise it to the second power: $x^2$.

Now let us put it together:

```{r complicated, eval=T}
complicated = function(x) {
   <<Xsquare>>
}
```

很简单吧?

事实证明,在 Rstudio 中,它仅在我们将所有内容编织在一起时才有效,而不是在运行单个块时.几乎是有道理的.

Turns out in Rstudio it works only when we knit everything together, but not on running a single chunk. Almost makes sense.

要解决这个问题,请在控制台中运行以下命令:knit("filename.Rmd").

To solve this, in run the following: knit("filename.Rmd") in the console.

这篇关于如何解释 Rmarkdown 中的复杂函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆