gpt4 book ai didi

r - 在代码块中使用 markdown 来定义大型函数

转载 作者:行者123 更新时间:2023-12-02 07:58:15 25 4
gpt4 key购买 nike

我想在大型项目中使用 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 好。这是相关的,例如用于大型 Shiny 服务器功能或类似的东西。任何想法我怎么能做到这一点?

最佳答案

在 R-markdown 中,您不能跨 block 定义对象(例如函数)(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"))
)
```

呈现为:

rmarkdown rendered

关于r - 在代码块中使用 markdown 来定义大型函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60639663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com