paste data as a variable in a template

I am trying to dynamically generate plots in Rmarkdown. Each plot is generated in a new tab. The below code works fine:

---
title: several tabs
output: html_document
---

```{r setup, include=FALSE}
library(plotly)
```


## Graphs {.tabset .tabset-pills}

```{r, include = FALSE}
template <- c(
  "### {{tab}}\n",
  "```{r, echo = FALSE, message=FALSE}\n",
  "plot_ly(x = rnorm(10))\n",
  "```\n",
  "\n"
)

p <- lapply(1:3, function(i) {
  knitr::knit_expand(
    tab = i,
    text = template)
})
```

r knitr::knit_child(text = unlist(p))

How can I dynamically paste in my data in the template? The below code results in an error because the data is evaluated as text rather then data:

```{r, include = FALSE}
template <- c(
  "### {{tab}}\n",
  "```{r, echo = FALSE, message=FALSE}\n",
  "plot_ly(x = {{ data }})\n",
  "```\n",
  "\n"
)

p <- lapply(1:3, function(i) {
data <- data.frame(
  value1 = c(1,4,6,7,8,19,20),
  value2=c(1,3,6,7,6,19,21)
)
  knitr::knit_expand(
    tab = i,
    data = data,
    text = template)
})
Error in parse(text = x, srcfile = src) : 
  <text>:4:0: Unexpected End of Entry
2: plot_ly(x = c(1, 4, 6, 7, 8, 19, 20)
3: 

this gives an error

Error in data.frame(value1 = c(1, 4, 6, 7, 8, 19, 20), value2 = c(1, 3,  : 
  arguments imply differing number of rows: 7, 8

so I'd start by having one less of value2

Sorry that was a typo. I changed it now.

I think you want to be passing the dataframe name into the template rather than the dataframe itself.
example

---
title: several tabs
output: html_document
---

```{r setup, include=FALSE,echo=FALSE}
library(plotly)
```


```{r, include = FALSE,echo=FALSE}
basedf <- data.frame(
  value1 = c(1,4,6,7,8,19,20)
) 
mydf1 <- basedf %>% mutate(value2=value1/2)
mydf2 <- basedf %>% mutate(value2=value1^2)
mydf3 <- basedf %>% mutate(value2=sqrt(value1))



template <- c(
  "### {{tab}}\n",
  "```{r, echo = FALSE, message=FALSE}\n",
  "plot_ly(data = {{dfname}}, x=~value1,y=~value2)\n",
  "```\n",
  "\n"
)

p <- lapply(1:3, function(i) {
  knitr::knit_expand(
    tab = i,
    dfname = paste0("mydf",i),
    text = template)
})

```

`r knitr::knit_child(text = unlist(p))`
2 Likes

Thanks a lot for the answer! The solution was to pass the data.set in the R chunk. It is explained here:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.