我想在大型项目上使用R Markdown。该项目使用许多非常大的自定义函数。因此,我想使用markdown对函数的某些部分进行注释。
```{r}
my_function <- function(x,y){
test <- x + seq(1,10)
```
然后我想用Markdown描述函数的第二部分
```{r}
output <- test + y
return(output)
}
```
然后我想应用该功能
```{r}
my_function(1,2)
```
当然,我意识到我可以简单地使用#符号添加注释,但这不如markdown好。例如,这与大型闪亮的服务器功能或类似功能有关。有什么想法我该怎么做?
在R-markdown中,您无法跨块(附加)定义对象(例如,函数)。一种选择是不可见地定义功能,然后使用非执行代码块来讨论各部分。但是我不喜欢这种选择,因为它使工作量加倍并且增加了使用不同功能的可能性。
一种替代方法是在函数中定义清晰的标记,抓住函数的主体,然后按这些标记拆分。尝试这个:
---
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"))
)
```
呈现为:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句