Can I pass a variable to the downloadthis command?
Closed this issue ยท 3 comments
Thanks again for creating this extension!
The example has this command:
{{< downloadthis files/mtcars.csv dname="mtcars.csv" label="Download the mtcars data" icon="database-fill-down" type="info" >}}
Where 'files/mtcars.csv' is a path to an existing file.
I'd love to pass the data frame directly, e.g. 'mtcars' instead of 'files.mtcars.csv'. Is this a possibility? If not, is it possible to pass a file path as a variable created within the quarto document? E.g.:
p <- path("mtcars", ext = "csv")
{{< downloadthis p dname="mtcars.csv" label="Download the mtcars data" icon="database-fill-down" type="info" >}}
Ah, with some experimentation I can do:
path <- fs::path("mtcars", ext = "csv")
cmd <- paste('{{< downloadthis', path, 'dname=Mtcars label="Download the mtcars data" icon=database-fill-down type=info class=data-button id=mtcars >}}')
Then:
#| results: asis
cat(cmd)
This works for my purposes, but passing in the data frame object directly would be ideal.
No! I am afraid It is not possible to pass R data.frame
directly to the downloadthis
shortcode ๐, since the shortcode is internally handled by Lua.
However, your solution to this problem can be made easier by implementing inline R code. Try the following reprex,
---
title: "Downloadthis Example"
format: html
---
## data.frame in downloadthis
### Approach 01
Assuming you have iris.csv file in the same directory as this qmd file, you can refer
the path of the csv using inline r code as follows,
{{< downloadthis `r fs::path("iris.csv")` dname=iris label="Download the iris data" icon=database-fill-down type=info class=data-button id=iris >}}
### Approach 02
You can write a function that takes a data.frame object and then writes the data.frame
then writes the data.frame in the current directory as a csv file then returns the
path to the csv file.
```{r}
#| echo: false
embed_df <- function(data, name) {
readr::write_csv(data, paste0(name, ".csv"))
fs::path(name, ext="csv")
}
```
Then call the function inside the downloadthis shortcode using inline R code.
{{< downloadthis `r embed_df(mtcars, "mtcars")` dname=Mtcars label="Download the mtcars data" icon=database-fill-down type=info class=data-button id=mtcars >}}
Let me know if anything is unclear ๐.
That's great, thanks!