You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Quarto中传递列表参数并实现遍历打印?

解决Quarto中列表参数无法遍历的问题

问题出在YAML参数的定义方式上:直接写list("A", "B")会被YAML解析为字符串,而非R的列表对象,所以遍历的时候只会打印整个字符串内容。

有两种可行的解决方法:

方法1:使用YAML原生列表格式

直接用YAML数组语法定义参数,Quarto会自动将其转换为R的字符向量(可直接遍历):

---
title: "`r params$report_title`"
author: "`r params$name`"
format: html
params:
  report_title: "main title"
  name: "author name"
  p_list: ["A", "B"]
---

Printing each element of the list...

```{r}
#| echo: true
for(p in params$p_list){
  print(p)
}

Printing the list...

#| echo: true
print(params$p_list)
运行后输出:
第一个代码块:

[1] "A"
[1] "B"

第二个代码块:

[1] "A" "B"

## 方法2:用`!expr`标记R表达式
如果需要传递真正的R列表(比如元素类型不同),可以用`!expr`告诉Quarto这是一段R代码,会被直接解析为R对象:

```yaml
---
title: "`r params$report_title`"
author: "`r params$name`"
format: html
params:
  report_title: "main title"
  name: "author name"
  p_list: !expr list("A", "B")
---

Printing each element of the list...

```{r}
#| echo: true
for(p in params$p_list){
  print(p)
}

Printing the list...

#| echo: true
print(params$p_list)
运行后输出:
第一个代码块:

[1] "A"
[1] "B"

第二个代码块:

[[1]]
[1] "A"

[[2]]
[1] "B"

内容的提问来源于stack exchange,提问作者Satya Pamidi
相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 19:46:01