Skip to content

Instantly share code, notes, and snippets.

@richarddmorey richarddmorey/demo.R
Last active Apr 3, 2019

Embed
What would you like to do?
Demonstrate reading bibtex for Rmarkdown from the web (e.g., from github)
# This file is to demonstrate the output.
# It is not needed.
testRmd = "https://gist.githubusercontent.com/richarddmorey/c4dd7d1fba2aa055a6f71286baedac25/raw/c256dd9f1ca0b22dfbce12443e1cb98ed5bb9d86/demo.Rmd"
tf = tempfile(fileext = ".Rmd")
tf_out = tempfile(fileext = ".html")
cat(RCurl::getURL(testRmd), file = tf)
rmarkdown::render(tf,output_file = tf_out)
browseURL(tf_out)
---
title: "Test reading bibtex from web"
output: html_document
bibliography: "`r devtools::source_gist(id = 'c4dd7d1fba2aa055a6f71286baedac25', filename = 'getbib.R'); getbib()`"
---
You'll need the devtools package installed for this to work. Alternatively, you can save the `getbib.R` file locally to prevent loading the function from the internet every time. Then just use `source()` instead of `devtools::source_gist()` (I really only used `devtools::source_gist` so that it would work for this demo).
This is a test [@Fisher:1955].
# References
# This function does the work of loading the bibtex file from the web
# and potentially saving it for offline use, refreshing it when it is too
# old
getbib <- function(file_name = "references.bib",
refresh_days = 0,
copy_to_current = FALSE,
URL = "http://drsmorey.org/bibtex/bibfile.php")
{
if( is.null(file_name) ){
file_name <- tempfile(fileext = ".bib")
}else if( file.exists(file_name) ){
file_age = difftime(Sys.time(),
file.mtime( file_name ),
units = "days")
if(file_age < refresh_days) return( file_name )
}
bib_content = RCurl::getURL(URL)
# iconv(bib_content, from = "CP1252", to = "UTF-8")
cat(bib_content, file = file_name)
if(copy_to_current){
file.copy( file_name, getwd() )
}
return(file_name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.