[英]knitr with bash: change working directory
I am using knitr for making a markdown report for some bash commands. 我正在使用knitr为一些bash命令制作降价报告。 However, my operations include changing a directory and creating a file there, so it would be ideal if I could use
cd
in my .Rmd file: 但是,我的操作包括更改目录和在那里创建文件,所以如果我可以在我的.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
```
However, the file myfile
is created in the directory from which I compile the document with knit
and not in mytest
. 但是,文件
myfile
是在我用knit
而不是mytest
编译文档的目录中创建的。 I guess a new bash shell is started for each code chunk. 我想为每个代码块启动一个新的bash shell。
I have seen discussions about setting cwd
in R ( https://github.com/yihui/knitr/issues/277 ) but not for bash. 我已经看过关于在R( https://github.com/yihui/knitr/issues/277 )中设置
cwd
讨论,但不是关于bash的讨论。
Is there a way of maybe setting a working directory for a code chunk? 有没有办法为代码块设置工作目录?
You may use Rscript
to run a .Rmd
file and include any "R code" within the command line to keep your code chunks intact. 您可以使用
Rscript
运行.Rmd
文件并在命令行中包含任何“R代码”以保持代码块完好无损。
Rscript -e "library(knitr); opts_knit\\$set(root.dir='~'); knit('test.Rmd')"
is an example bash command to run the test.Rmd
file below. Rscript -e "library(knitr); opts_knit\\$set(root.dir='~'); knit('test.Rmd')"
是一个示例bash命令,用于运行下面的test.Rmd
文件。 You may change the root.dir
to suit your needs. 您可以更改
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*
```
The output: 输出:
```
## mytest:
## myfile
##
## mytest2:
## myfile2
```
Another way of looking at it would be to create every folder and file from where you are, and not move around with cd. 查看它的另一种方法是从你所在的位置创建每个文件夹和文件,而不是使用cd。
mkdir accepts more than one argument 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
To easily change the folder structure from a one central variable: 要从一个中心变量轻松更改文件夹结构:
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.