Home > Enterprise >  Adding citations with R code in Rmarkdown document
Adding citations with R code in Rmarkdown document

Time:07-29

To add a citation in Rmarkdown we can just type [@Author] in the document. I wonder if it's possible to do this with R code.

The pseudo code for my expected solution:

# just markdown
This is my markdown content and here is a great book about it: `r insert_citation()`.

where insert_citation is a function like this:

insert_citation <- function() "[@Author]"

This should produce the output like this (assuming I already prepared the bibliography for the document):

This is my markdown content and here is a great book about it: (A. Uthor 2021).

The point is that I need to add a citation conditionally based on data. If a condition is satisfied there should be the citation in the document, otherwise skip the citation. My document is a docx. Any hints related to officedown or officer packages are welcome.

CodePudding user response:

One way to achieve this is to use invisible() and a wrapper around cite.

---
title: "cite"
output: word_document
bibliography: refs.bib
---
```{r refs, include=FALSE}
db <- bibentry(
   bibtype = "Manual",
   title = "R: A Language and Environment for Statistical Computing",
   author = person("R Core Team"),
   organization = "R Foundation for Statistical Computing",
   address = "Vienna, Austria",
   year = 2013,
   url = "https://www.R-project.org/",
   key = "R")

f <- function(cond, ref) if(cond) cite(ref, db) else invisible()
```

This is some text `r f(TRUE, "R")` but don't cite this `r f(FALSE, "R")`

`r if(TRUE) "[@R]"` but not `r if(FALSE) "[@R]"`

enter image description here

If you have a bib file, simply returning a string with the regular citation structure is sufficient, as shown in the last line.

There are likely better alternatives such as parameterized reports if you have to do this for multiple reports or multiple references.

  • Related