Skip to content

Instantly share code, notes, and snippets.

@RaphaelS1
Last active November 25, 2023 10:43
Show Gist options
  • Save RaphaelS1/4120c2bc6034182cd56e26ac9b7b1827 to your computer and use it in GitHub Desktop.
Save RaphaelS1/4120c2bc6034182cd56e26ac9b7b1827 to your computer and use it in GitHub Desktop.
Create a .ris file from an R citation
#' riscitation - Create .ris file from R citation
#'
#' Suggests:
#' Package `berryFunctions` if `opendelete = TRUE`.
#'
#' Arguments
#' `pkg:character(1)` - Name of package to cite
#' `path:character(1)` - Path to write file too, should include file name but not extension
#' `opendelete:logical(1)` - If `TRUE` (default), opens the .ris file in the default application then deletes
#' the file.
#'
#' Usage
#' riscitation("mlr3proba", "~/Desktop/cite_mlr3proba", FALSE)
#' riscitation("mlr3proba", tempfile(), TRUE)
riscitation <- function(pkg, path = tempfile(), opendelete = TRUE) {
fileConn = file(paste0(path, ".ris"))
# usual warnings are for missing fields
c = suppressWarnings(unclass(citation(pkg))[[1]])
TY = paste("TY -",
switch(attr(c, "bibtype"),
Book = "BOOK",
Article = "JOUR",
"COMP"
)
)
T1 = paste("T1 -", c$title)
revname = function(name) {
spl = strsplit(as.character(name), split = " ", fixed = TRUE)[[1]]
first = paste0(spl[2:length(spl)], collapse = " ")
paste(first, spl[[1]], sep = ", ")
}
A1 = c()
for(i in seq_along(c$author)) {
auth = c$author[[i]]
mtc = regexpr(" <|\\[", auth)
if(mtc != -1) {
auth = substr(auth, 1, regexpr(" <|\\[", auth) - 1)
}
auth = revname(auth)
A1 = c(A1, paste("A1 -", auth))
}
Y1 = paste0("Y1 - ", c$year, "///")
DO = paste("DO -", c$doi)
JF = paste("JF -", c$journal)
VL = paste("VL -", c$volume)
IS = paste("IS -", c$number)
UR = paste("UR -", c$url)
SN = paste("SN -", c$isbn)
N1 = paste("N1 -", c$note)
pages = c$pages
if(!is.null(pages)) {
mtc = regexpr("-", pages, fixed = TRUE)
if (mtc != -1) {
SP = paste("SP -", substr(pages, 1, mtc - 1))
EP = paste("EP -", substr(pages, mtc + 1, 1000))
} else {
SP = paste("SP -", pages)
EP = paste("EP -", pages)
}
} else {
SP = "SP - "
EP = "EP - "
}
PB = paste("PB -", if(is.null(c$publisher)) "CRAN" else c$publisher)
x = c(TY, T1, A1, Y1, DO, JF, VL, IS, UR, SN, N1, SP, EP, PB)
writeLines(x, fileConn)
close(fileConn)
if (opendelete) {
berryFunctions::openFile(paste0(path, ".ris"))
file.remove(paste0(path, ".ris"))
}
}
@mr-september
Copy link

How do you generate a citation for R itself?

@RaphaelS1
Copy link
Author

@mr-september I believe riscitation('base')

@mr-september
Copy link

Thank you!

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