gpt4 book ai didi

r - 在 R knitr 中调用后放置函数定义

转载 作者:行者123 更新时间:2023-12-04 16:59:25 25 4
gpt4 key购买 nike

快速且可能是愚蠢的问题:在 R markdown/knitr 文档中,是否可以在实际调用函数后将函数定义放在文档的末尾(例如在附录中)?

最佳答案

Is it possible to put a function definition at the end of the document, after the function is actually called?



从技术上讲,没有。一个函数需要在调用之前定义。但是,由于问题涉及 knitr应该改写:

Is it possible to show a function definition at the end of the document, after the function is actually called?



是的,有几种方法可以实现这一点。请注意,选项 2 和 3 可以在 Print highlighted source code of a function 中找到。 .

选项 1:重用块

在使用之前定义函数。
```{r definition, echo = FALSE}
myfun <- function(x) {
return(sprintf("You passed me %s", x))
}
```

Use the function:
```{r}
myfun(123)
```

Show the chunk where it was defined:
```{r definition, eval = FALSE}
```

与另一个非空块具有相同标签的空块“继承”后者的代码。这在 How to reuse chunks 中有描述.
块内的代码 definition一开始是隐藏的( echo = FALSE )。稍后打印代码时,使用 eval = FALSE以避免再次评估代码。

当函数在单独的块中定义时,此选项很方便。

选项 2:简单 print
这是最简单的选项,但输出不会突出显示语法。只需在隐藏块中定义函数,使用它并稍后打印函数定义:
Define the function *before* it is used.

```{r definition, echo = FALSE}
myfun <- function(x) {
return(sprintf("You passed me %s", x))
}
```

Use the function:
```{r}
myfun(123)
```


```{r}
myfun
```

选项 3:生成包含函数定义的块

此选项在 Yihui's website 上有所描述.它使用函数 insert_fun生成一个包含函数定义的块。
insert_fun = function(name) {
read_chunk(lines = capture.output(dump(name, '')), labels = paste(name, 'source', sep = '-'))
}

这种方法非常灵活,因为函数是在单独的块中定义还是在 source 的文件中定义都没有关系。 d.
insert_fun获取函数的名称(如 character )并创建一个标记为 functionname-source 的块:
Define the function *before* it is used.

```{r definition, echo = FALSE}

# Define your function.
myfun <- function(x) {
return(sprintf("You passed me %s", x))
}

library(knitr)

# Define insert_fun.
insert_fun = function(name) {
read_chunk(lines = capture.output(dump(name, '')), labels = paste(name, 'source', sep = '-'))
}

insert_fun("myfun") # creates a chunk labelled "myfun-source"
```

Use the function:
```{r}
myfun(123)
```


```{r myfun-source, eval = FALSE}
```

关于r - 在 R knitr 中调用后放置函数定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32688936/

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