【问题标题】:knitr with bash: change working directory带有 bash 的 knitr:更改工作目录
【发布时间】:2015-07-31 08:22:00
【问题描述】:

我正在使用 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 设置的讨论。

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

【问题讨论】:

  • 你看opts_knit$set(root.dir = "...")setwd("...")了吗?
  • 是的,但是这些都是 R 函数,我的代码块中没有任何 R 代码。我只使用 R 来调用knit。所以我看不到在块之间更改 cwd 的可能性......
  • 这是一个已知问题。请参阅yihui.name/knitr/demo/engines 的最后一段,另请参阅github.com/yihui/runr 我不太确定runr 在bash 引擎方面是否仍然可以正常工作。
  • 谢谢!我去看看runr

标签: r bash markdown knitr cd


【解决方案1】:

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

【讨论】:

  • 这里options中设置的root.dir没有效果;您的解决方案会在创建的目录中创建文件,因为 cdtouch 在同一个代码块中。
  • 我看到你提到的同样的问题,@user1981275。目录永远不会改变,一切都保留在文档目录中。
【解决方案2】:

另一种看待它的方法是从你所在的位置创建每个文件夹和文件,而不是用 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.

【讨论】:

    猜你喜欢
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多