繁体   English   中英

knitr with bash:更改工作目录

[英]knitr with bash: change working directory

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

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的讨论。

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

您可以使用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*
```

输出:

```
## mytest:
## myfile
##
## mytest2:
## myfile2
```

查看它的另一种方法是从你所在的位置创建每个文件夹和文件,而不是使用cd。

创建目录树

mkdir接受多个参数

mkdir -p 'plots/scatter' 'plots/box'
# creates plots folder in the working directory,
# and then creates scatter and box folders in it.

在那里创建文件

touch 'plots/scatter/firstfile.txt' 'plots/scatter/secondfile.txt'
# single quotes mean literals

将关键部分保留为变量

要从一个中心变量轻松更改文件夹结构:

scatter_folder=plots/scatter
touch "$scatter_folder/third_file.txt" "$scatter_folder/fourth_file.txt"
# double quotes allow for variable substitution.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM