我已经在源 Rmd 文件中运行了分析,并且希望仅使用few来自源的块。我已经看到了一些关于从源 Rmd 中提取所有块的答案来自另一个 Rmd 中的 Rmd 文件的源代码 https://stackoverflow.com/questions/41962434/source-code-from-rmd-file-within-another-rmd and 如何获取像 `source('myfile.r')` 这样的 R Markdown 文件? https://stackoverflow.com/questions/10966109/how-to-source-r-markdown-file-like-sourcemyfile-r。我对这些帖子有同样的担忧,因为我不想移植一个单独的 .R 文件,这似乎是唯一的方法read_chunk
works.
我想我现在可以导入源 Rmd,但现在我不确定如何在最终的 Rmd 中调用它的特定块。这是一个可重现的示例:
源代码.Rmd
---
title: "Source Code"
output:
pdf_document:
latex_engine: xelatex
---
```{r}
# Load libraries
library(knitr) # Create tables
library(kableExtra) # Table formatting
# Create a dataframe
df <- data.frame(x = 1:10,
y = 11:20,
z = 21:30)
```
一些解释性文字
```{r table1}
# Potentially big block of stuff I don't want to have to copy/paste
# But I want it in the final document
kable(df, booktabs=TRUE,
caption="Big long title for whatever") %>%
kable_styling(latex_options=c("striped","HOLD_position")) %>%
column_spec(1, width="5cm") %>%
column_spec(2, width="2cm") %>%
column_spec(3, width="3cm")
```
[一些其他文本,加上一堆我不需要任何人在干净版本中看到的其他块。]
```{r}
save(df, file="Source.Rdata")
```
最终文件Rmd
---
title: "Final Doc"
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include=FALSE}
# Load libraries and data
library(knitr) # Create tables
library(kableExtra) # Table formatting
opts_chunk$set(echo = FALSE)
load("Source.Rdata")
```
据我所知,这可能是加载的最佳方式SourceCode.Rmd
(来自上面第一个链接来源):
```{r}
options(knitr.duplicate.label = 'allow')
source_rmd2 <- function(file, local = FALSE, ...){
options(knitr.duplicate.label = 'allow')
tempR <- tempfile(tmpdir = ".", fileext = ".R")
on.exit(unlink(tempR))
knitr::purl(file, output=tempR, quiet = TRUE)
envir <- globalenv()
source(tempR, local = envir, ...)
}
source_rmd2("SourceCode.Rmd")
```
此时,我不知道如何调用特定块table1
from SourceCode.Rmd
。我已按照说明尝试了以下操作here http://zevross.com/blog/2014/07/09/making-use-of-external-r-code-in-knitr-and-r-markdown/没有成功:
```{r table1}
```
```{r}
<<table1>>
```
第一个似乎什么也没做,第二个抛出一个unexpected input in "<<"
error.