如何从 URL 编织子文档

How to knit a child document from a URL

我想从 github 中拉出子文档以编织为 rmarkdown 文档中的子项。

使用 allowing child markdown files 中的 yihui 示例,我们可以有一个主文档(已修改)引用 github 上的子文档,而不是先下载它。

我已经解决了 Windows 兼容性问题,现在 setwd() 失败了。

如何正确设置 knitr 文档以编织来自 URL 的子项目? (如果可能的话)

初始(windows)

You can also use the `child` option to include child documents in markdown.

```{r test-main, child='https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd'}
```

You can continue your main document below, of course.

```{r test-another}
pmax(1:10, 5)
```

错误输出

## Quitting from lines 4-4 (https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd) 
## Error in readLines(if (is.character(input2)) { : 
##   cannot open the connection
## Calls: <Anonymous> ... process_group.block -> call_block -> lapply -> FUN -> knit -> readLines
## In addition: Warning message:
## In readLines(if (is.character(input2)) { : unsupported URL scheme
## Execution halted

这是错误的,因为 readLines 命令在处理 Windows 时默认无法访问 HTTPS。

v2(在 windows 上)

为了更正 readLines 问题,我添加了一个块以增加访问 HTTPS 的能力

You can also use the `child` option to include child documents in markdown.

```{r setup, results='hide'}
setInternet2(use = TRUE)
```

```{r test-main, child='https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd'}
```

You can continue your main document below, of course.

```{r test-another}
pmax(1:10, 5)
```

错误输出

## processing file: https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd
## Quitting from lines 2-2 (https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd) 
## Quitting from lines NA-7 (https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd) 
## Error in setwd(dir) : cannot change working directory
## Calls: <Anonymous> ... process_group.inline -> call_inline -> in_dir -> setwd
## Execution halted

尝试将 setwd("~") 添加到块 setup 中对错误消息没有影响

我不认为你可以这样做,因为据我所知,在编织过程中会发生目录更改(到子文档的目录)。因为您的子文档不是本地文件,隐式 setwd 将失败。

一个解决方案是添加一个隐藏块,将 github 文件下载到一个临时目录,然后删除下载的文件。类似于:

```{r setup, echo=FALSE, results='hide'}
setInternet2(use = TRUE)
x <- tempfile(fileext = "Rmd")
on.exit(unlink(x))
download.file("https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd", x)
```

```{r test-main, child=x}
```

You can continue your main document below, of course.

```{r test-another}
pmax(1:10, 5)
```

如果 child 只是降价(没有要处理的 R 代码),那么这可能对你有用。

```{r footer, echo=FALSE, results='asis'}
url <- "https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd"
childtext <- readLines(url)
cat(childtext, sep="\n")
```