如何从URL编织子文档

时间:2015-04-06 12:41:52

标签: r knitr r-markdown

我希望将来自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

这是错误的,因为在Windows上工作时,readLines命令默认无法访问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中对错误消息没有影响

2 个答案:

答案 0 :(得分:4)

我认为你不能这样做,因为根据我的理解,在编织过程中会有一个目录更改(到子文档的目录)。由于您的子文档不是本地文件,因此隐式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)
```

答案 1 :(得分:1)

如果孩子只是降价(没有要处理的 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")
```