Home > Enterprise >  how to pass a list as parameter in quarto to later loop through that list
how to pass a list as parameter in quarto to later loop through that list

Time:12-29

I want to pass a list as parameter so that I can loop through that list and print something. Here is a simple example:

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

Printing each element of the list...

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

Printing the list...
```{r}
#| echo: true
print(params$p_list)
```

Output for first chunk

[1] "list(\"A\", \"B\")"

for second chunk

[1] "list(\"A\", \"B\")"

How to untangle this list so that I can print A and B separately? thanks in advance.

CodePudding user response:

Here params$p_list is a string and we turn this into an R list using eval(parse(text = params$p_list)).

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

Printing each element of the list...

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

Printing the list...
```{r}
#| echo: true
print(eval(parse(text = params$p_list)))
```

list as parameters


See the Q/A Evaluate expression given as a string for more potential options to solve your case.

  • Related