knitr with bash:更改工作目录

use*_*275 6 bash markdown cd r knitr

我正在使用knitr为一些bash命令制作降价报告.但是,我的操作包括更改目录和在那里创建文件,所以如果我可以cd在我的.Rmd文件中使用它将是理想的:

make a directory
```{r mkdir, engine='bash'}
mkdir mytest
```
cd into directory
```{r cd, engine='bash'}
cd mytest
```
create file
```{r create, engine='bash'}
touch myfile
```
check contents
```{r ls, engine='bash'}
ls
```
Run Code Online (Sandbox Code Playgroud)

但是,该文件myfile是在我使用knit而不是编译文档的目录中创建的mytest.我想为每个代码块启动一个新的bash shell.

我已经看过有关cwd在R(https://github.com/yihui/knitr/issues/277)中进行设置的讨论,但对于bash没有.

有没有办法为代码块设置工作目录?

xb.*_*xb. 0

您可以用来Rscript运行.Rmd文件并在命令行中包含任何“R 代码”,以保持代码块完整。

Rscript -e "library(knitr); opts_knit\$set(root.dir='~'); knit('test.Rmd')"是运行下面文件的 bash 命令示例test.Rmd。您可以更改root.dir以满足您的需要。

make directories
```{r mkdir, engine='bash'}
mkdir mytest
mkdir mytest2
```

create one file in the 1st dir
```{r create, engine='bash'}
cd mytest
touch myfile
```

create another file in the 2nd dir
```{r create2, engine='bash'}
cd mytest2
touch myfile2
```

check contents
```{r ls, engine='bash'}
ls mytest*
```
Run Code Online (Sandbox Code Playgroud)

输出:

```
## mytest:
## myfile
##
## mytest2:
## myfile2
```
Run Code Online (Sandbox Code Playgroud)