RMarkdown:如何将参数传递给 R 中定义为变量的 bash 块?

Ole*_*leg 5 bash r r-markdown

交叉发布

我想使用 R 环境中定义的变量作为 bash 块中的参数。有什么办法可以做到这一点吗?

例如,在下面的示例中,我想使用 R 定义脚本的路径并将其作为参数传递给 bash:

```{r}
path_to_script <- glue("{here::here()}/bash_scripts/script.sh")
\```

```{bash}
bash  **path_to_script**
\```
Run Code Online (Sandbox Code Playgroud)

use*_*330 7

我不认为 knitrbash引擎会进行任何替换,但您应该能够写入环境变量,并从 bash 使用它。

例如,

---
title: "Untitled"
date: "09/12/2021"
output: html_document
---


```{r}
msg <- shQuote("This is a message from R.")
Sys.setenv(R_MESSAGE = msg)
```

```{bash}
echo $R_MESSAGE
```
Run Code Online (Sandbox Code Playgroud)

产生以下输出:

在此输入图像描述

shQuote()在阅读@Fravadona 的评论后添加了该调用:这绝对是一个非常好的主意,因为您正在构建的路径可能包含空格或其他特殊字符。