Reputation: 53
I need some help to automatically list all *.bib files in ../bib
directory for bibliography field in Rmd YAML using list.files()
function.
I have three bib files ("a.bib", "b.bib", "c.bib") in ../bib directory. Without having to manually type in every file name in bibliography field of YAML, I would like to automatically parse each bib file name with its relative path for the field so that I just simply add more bib files in the "bib" directory whenever I need more references. I have tried some possible code like below; however, it failed. Any help would be greatly appreciated.
---
title: "Test Document"
output: pdf_document
bibliography: ['`r paste0("bib/", list.files("bib", pattern = "(*.bib)$"))`']
---
# Intro
This is test.
I would like to have the bibliography
field in YAML is filled with the existing *.bib file name list (with their relative path) as follows:
bibliography: ["bib/a.bib", "bib/b.bib", "bib/c.bib"]
Upvotes: 2
Views: 186
Reputation: 543
You seem to be on track with using single quotes to indicate executable R code in your YAML header, but nothing I have tried seems to work. This might not be possible...
Rather than trying to execute an expression that references each .bib
file in your YAML header, why not create a new, merged bibliography.
To create a merged bibliography, you can use the bib2df package.
Try the following code:
# Load the bib2df library.
library(bib2df)
# Set path to .bib files.
bib_path <- paste0(getwd(),"/bib")
# Create vector of all .bib files.
bib_refs <- list.files(path=bib_path,pattern = ".bib")
# Create an empty list for storing bib data frames.
bibs_list <- list()
# Loop through bib_refs and store as df in bibs_list
for (i in 1:length(bib_refs)){
ref_path <- paste0(bib_path,"/",bib_refs[i])
bibs_list[[i]] <- bib2df(ref_path)
}
# bind dfs in list.
bibs_df <- do.call(rbind,bibs_list)
# Create new merged bibliography
df2bib(bibs_df, file = paste0(bib_path,"/","bibliography.bib"))
Now you will probably need to specify a path to your .bib
files that differs from your working directory, where you are rendering the .R or .Rmd file. To do this, I changed my YAML header to look like this:
bibliography: D:\\Documents\\R\\StackOverflow\\bib\\bibliography.bib
Upvotes: 2