2015-05-19 92 views
5

我正在使用knitr制作一些bash命令的markdown报告。然而,我的操作包括改变一个目录,并创建一个文件在那里,所以这将是理想的,如果我能在我的.Rmd文件中使用cdknitr with bash:更改工作目录

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 
``` 

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

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

有没有办法可以设置代码块的工作目录?

+1

你看看'opts_knit $组(root.dir = “... ”)'和'setwd(“ ...”)'? – pfuhlert

+0

是的,但这些都是R函数,而且我的大块中没有任何R代码。我只用R来调用'knit'。所以我没有看到在大块之间改变CWD的可能性...... – user1981275

+2

这是一个已知的问题。请参阅http://yihui.name/knitr/demo/engines/的最后一段。另请参阅https://github.com/yihui/runr我不太确定Runr在bash方面是否仍然运行良好'引擎。 –

回答

0

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

Rscript -e "library(knitr); opts_knit\$set(root.dir='~'); knit('test.Rmd')"是运行下面的test.Rmd文件的示例bash命令。您可以更改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* 
``` 

输出:

``` 
## mytest: 
## myfile 
## 
## mytest2: 
## myfile2 
``` 
+0

他在root.dir中设置的选项在这里没有任何影响;您的解决方案会在创建的目录中创建文件,因为'cd'和'touch'位于相同的代码块中。 – user1981275

+0

我看到你提到的同样的问题,@ user1981275。 dir永不改变,一切都停留在文档目录中。 – pauljohn32