在代码块中使用 Markdown 来定义大型函数

Mor*_*arz 2 r r-markdown shiny

我想在一个大型项目中使用 R Markdown。该项目使用了许多非常大的自定义函数。因此,我想使用 Markdown 来评论该功能的某些部分。

```{r}
my_function <- function(x,y){
  test <- x + seq(1,10)
```
Run Code Online (Sandbox Code Playgroud)

然后我想用Markdown来描述函数的第二部分

```{r}
  output <- test + y
  return(output)
}
```
Run Code Online (Sandbox Code Playgroud)

然后我想应用该功能

```{r}
my_function(1,2)
```
Run Code Online (Sandbox Code Playgroud)

当然我意识到我可以简单地使用 # 符号来添加注释,但这不如 markdown 好。这是相关的,例如大型闪亮的服务器功能或类似的东西。任何想法我怎么能做到这一点?

r2e*_*ans 6

在 R-markdown 中,您不能跨块(afaict)定义对象(例如,函数)。一种替代方法是不可见地定义函数,然后使用非执行代码块来讨论这些部分。但我不喜欢这种替代方案,因为它会加倍努力并增加具有不同功能的可能性。

一种替代方法是在函数中定义清晰的标记,获取函数的主体,然后通过这些标记进行拆分。尝试这个:

---
title: test markdown
---

```{r echo = FALSE, include = FALSE}
my_function <- function(x,y){
  test <- x + seq(1,10) ###BREAK###
  # normal comment
  output <- test + y    ###BREAK###
  return(output)
}
my_function_body <- strsplit(
  paste(head(capture.output(print.function(my_function)), n = -1), collapse = "\n"),
  "###BREAK###[\n\r]*")[[1]]
```

```{r echo = FALSE, include = TRUE, comment = ''}
cat(my_function_body[[1]])
```

Then I would like to use Markdown to describe the second part of the function


```{r echo = FALSE, include = TRUE, comment = ''}
cat(my_function_body[[2]])
```

Now the third/last part of the function


```{r echo = FALSE, include = TRUE, comment = ''}
cat(my_function_body[[3]])
```

And then I would like to apply the function

```{r}
my_function(1,2)
```

And the whole of the function (excluding the markers):

```{r echo = FALSE, include = TRUE, comment = ''}
cat(
  gsub("###BREAK###", "",
       paste(head(capture.output(print.function(my_function)), n = -1), collapse = "\n"))
)
```
Run Code Online (Sandbox Code Playgroud)

这呈现为:

rmarkdown 渲染