Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在RMarkdown中包含来自外部源R的函数_R_R Markdown_Knitr - Fatal编程技术网

在RMarkdown中包含来自外部源R的函数

在RMarkdown中包含来自外部源R的函数,r,r-markdown,knitr,R,R Markdown,Knitr,假设我有一个functions.R脚本,其中定义了几个函数: foo我采用从到相关问题的方法来解决这个问题。1 我将上述两个示例函数存储在文件functions.R中: foo <- function(x) print(x-2) bar <- function(x) print(x^3) 然后我们的文档呈现为 1该问题和答案(1)不在R标记的上下文中,更重要的是(2)仅演示了如何从R脚本获取所有函数(而不获取其他对象),而不是特定函数。如果您知道您想要的函数在哪一行,您可以采用

假设我有一个
functions.R
脚本,其中定义了几个函数:

foo我采用从到相关问题的方法来解决这个问题。1

我将上述两个示例函数存储在文件
functions.R
中:

foo <- function(x) print(x-2)
bar <- function(x) print(x^3)
然后我们的文档呈现为



1该问题和答案(1)不在R标记的上下文中,更重要的是(2)仅演示了如何从R脚本获取所有函数(而不获取其他对象),而不是特定函数。

如果您知道您想要的函数在哪一行,您可以采用这种方法,谢谢@duckmayr,我不知道我能做到。但是我有点不愿意这样做,因为可能会对脚本进行更改(在某处添加/删除几行),这会把事情搞砸;现在添加一个更健壮的方法太棒了!有没有一种方法像其他函数一样,将函数的原始代码包含在输出中?(就像写在区块中的代码一样,区块定义中的
code=readLines(“functions.R”)
对整个脚本都有作用。)@ManuelHaqi当然,很容易。答案已更新为包含该功能再次感谢@duckmayr。实际上我的意思有点不同:我希望函数
echo
ed作为输出中的一段代码。我已经在这本书中展示了这一点。您更新的解决方案给出了A,但我的意思是B(或C)。啊,我明白了。。。我认为这会更加困难。如果我以后有时间的话,我会看看能不能弄明白
foo <- function(x) print(x-2)
bar <- function(x) print(x^3)
---
title: "SO Answer"
author: "duckmayr"
date: "7/8/2019"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

We set up a function to source an R script, but only assign to the global environment the functions we want:

```{r source_function}
source_functions <- function(fcn_names, file_name) {
    env <- new.env()
    source(file_name, local = env)
    for ( i in 1:length(fcn_names) ) {
        assign(fcn_names[i], get(fcn_names[i], envir = env), envir = .GlobalEnv)
    }
}
```

Then we can call it to get *only* the function `foo()`:

```{r get_foo}
source_functions("foo", "functions.R")
ls()
```

This will also work for multiple functions:

```{r get_foo_and_bar}
source_functions(c("foo", "bar"), "functions.R")
ls()
```
source_functions <- function(fcn_names, file_name) {
    env <- new.env()
    source(file_name, local = env)
    n <- length(fcn_names)
    result <- character(n)
    for ( i in 1:n ) {
        name <- fcn_names[i]
        fcn <- get(name, envir = env)
        code <- capture.output(show(fcn))
        code <- paste(code[-which(grepl("<env", code))], collapse = " ")
        assign(name, fcn, envir = .GlobalEnv)
        result[i] <- paste(name, "<-", code, collapse = " ")
    }
    return(result)
}