在探索了几个替代方案之后,我从包stringr 中找到了函数str_extract()。
在这里,我假设您有一个 bibtex 库,其中包括所有引用的参考文献(通常更多)。
由于 bibtexkey 样式不同,我还将Oto Kaláb 的示例与自己的示例结合在一起。
首先是 Rmd 文档。
rmd_text <- c("# Introduction",
"",
"Lorem ipsum dolor sit amet [@bibkey_a], consectetur adipisici elit [@bibkey_b],",
"sed eiusmod tempor incidunt ut labore et dolore magna aliqua [@bibkey_c;@bibkey_d].",
"",
"According to @Noname2000, the world is round [@Ladybug1999;Ladybug2009].",
"This knowledge got lost [@Ladybug2009a].")
writeLines(rmd_text, "document.Rmd")
下一个代码块被注释。最后我们得到一个包含所有引用的向量,可以被unique()压缩。
# Bibtexkeys from bib file
keys <- c("bibkey_a", "bibkey_b", "bibkey_c", "bibkey_d",
"Noname2000", "Ladybug1999", "Ladybug2009", "Ladybug2009a")
keys <- paste0("@", keys)
# Read document
document <- readLines("document.Rmd")
# Scan document line by line
cited_refs <- list()
for(i in 1:length(document)) {
cited_refs[[i]] <- str_extract(document[i], keys)
}
# Final output
cited_refs <- unlist(cited_refs)
cited_refs <- cited_refs[!is.na(cited_refs)]
summary(as.factor(cited_refs))
然后可以聚合得到的向量以了解文本中出现的频率(我认为这对于检测稀有引用也很有用)。我也在考虑在输出中提取“行号”。