Skip to content

Instantly share code, notes, and snippets.

@mattansb
Created July 21, 2025 20:03
Show Gist options
  • Select an option

  • Save mattansb/6f99540a30c3ef0d6939965fdc738de0 to your computer and use it in GitHub Desktop.

Select an option

Save mattansb/6f99540a30c3ef0d6939965fdc738de0 to your computer and use it in GitHub Desktop.
How to add packages to a .bib file from within a .qmd file
---
format: html
bibliography: [references.bib, packages.bib]
---
<!-- The `references.bib` files is for other, non-package, references. -->
```{r setup}
#| include: false
# This function takes package names as characters
# - checks they're installed
# - saves them for later
# - prints them out as @R-<package names>
citepkg <- function(...) {
pkg <- c(...)
stopifnot(insight::check_if_installed(pkg, stop = TRUE, prompt = FALSE))
pkgs2cite <- getOption("pkgs2cite", default = NULL)
options(pkgs2cite = c(pkgs2cite, pkg))
paste0(paste0("@R-", pkg), collapse = "; ")
}
```
All analyses were carried out in R [`r citepkg("base")`]
using some really amazing packages [`r citepkg("tidyverse", "ggplot2")`].
<!-- See comment below for how this works out. -->
# References
<!-- Then right before the references add this chunk - and that's it! -->
```{r write-bib}
#| include: false
#| echo: false
pkgs2cite <- getOption("pkgs2cite", default = NULL)
pkgs2cite <- unique(c("base", pkgs2cite))
knitr::write_bib(pkgs2cite, file = "packages.bib")
```
::: {#refs}
:::
@mattansb

Copy link
Copy Markdown
Author

This is how those citations are rendered in the .md file:

All analyses were carried out in R [@R-base] 
using some really amazing packages [@R-tidyverse; @R-ggplot2].

Which results in:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment