#' Function for creatng the reference file of the markdown documents in the working directory.
#' @return A bib file.
#' @importFrom tibble column_to_rownames
#' @importFrom tibble rownames_to_column
#' @importFrom tibble remove_rownames
#' @importFrom dplyr filter
#' @importFrom dplyr mutate
#' @importFrom dplyr %>%
#' @importFrom dplyr bind_rows
#' @importFrom dplyr group_by
#' @importFrom dplyr ungroup
#' @importFrom dplyr sample_n
#' @importFrom dplyr mutate_all
#' @importFrom tidyr unnest
#' @importFrom purrr map
#' @importFrom stringr str_detect
#' @importFrom stringr str_extract_all
#' @importFrom stringr str_replace_all
#' @importFrom stats na.omit
#' @importFrom utils read.csv
#' @importFrom utils write.csv
#' @importFrom utils installed.packages
#' @importFrom RefManageR ReadBib
#' @importFrom readr read_file
#' @importFrom RefManageR WriteBib
#' @importFrom RefManageR as.BibEntry
#' @export
gen_bib <- function() {
# Bind variables
year <- NULL
number <- NULL
volume <- NULL
key <- NULL
title <- NULL
abstract <- NULL
Freq <- NULL
# Obtain references
if ("bibliogr" %in% row.names(installed.packages())){
biblio <- bibliogr::references
} else {
biblio <- rstudioapi::selectFile(caption = "Select the database of references")
if (stringr::str_detect(biblio, ".bib$")) {
bilbio <- ReadBib(biblio) %>%
as.data.frame() %>%
rownames_to_column("key") %>%
mutate(
year = as.integer(year),
number = as.integer(number),
volume = as.integer(volume)
)
} else {
biblio <- read.csv(biblio, stringsAsFactors = FALSE)
}
}
# Gather citations
files <- list.files(getwd())
rmdfiles <- tibble::tibble(rmdfiles = files[stringr::str_detect(files, ".Rmd$")])
if (nrow(rmdfiles) > 0){
content <- rmdfiles %>%
dplyr::mutate(text = purrr::map(rmdfiles, read_file)) %>%
tidyr::unnest()
content <- paste(as.character(unlist(content$text)), collaspe = " ")
}
selection <- content %>%
str_extract_all("@\\w+") %>%
unlist() %>%
str_remove_all("@") %>%
unique()
# Create bib file
if (length(selection) > 0 & nrow(biblio) > 0){
basebib <- biblio %>%
dplyr::filter(key %in% selection) %>%
as.data.frame()
bib <- basebib %>%
mutate_all(str_replace_all, pattern = "&", replacement = "\\\\&") %>%
mutate(
title = paste0("{", title,"}"),
abstract = paste0("{", abstract,"}")
) %>%
unique() %>%
group_by(key) %>%
sample_n(1) %>%
ungroup() %>%
as.data.frame()
journal_rank <- bib$journal %>%
table() %>%
as.data.frame() %>%
arrange(-Freq)
write.csv(journal_rank, "journal_rank.csv", row.names = FALSE)
author_rank <- bib$author %>%
stringr::str_extract_all("^(.*?), | and(.*?),") %>%
unlist() %>%
stringr::str_remove_all(" and ") %>%
str_remove_all(",") %>%
trimws() %>%
table() %>%
as.data.frame() %>%
arrange(-Freq)
write.csv(author_rank, "author_rank.csv", row.names = FALSE)
bib <- bib %>%
split(f = bib$key) %>%
as.BibEntry() %>%
WriteBib(file = "ref.bib", append = FALSE)
}
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.