Search code examples
rbibtex

Convert a Bibtex class object to a series of text strings formatted for each citation


I'm new to bibTex objects, and want to generate a list of text strings for each citation in the object as a formatted citation. I don't want to generate a document--these strings will be used for a downstream purpose within R. Is there a way to do this? I can't even really figure out how to access the pieces of each citation in a bibTex object.

Put another way, how to I turn this:

   temp <- toBibtex(c(citation("base"), citation("sp")))

into this:

  [[1]]
  [1] "R Core Team (2019). R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria. https://www.R-project.org/."

  [[2]]
  [1] "Pebesma, E.J., R.S. Bivand (2005). Classes and methods for spatial data in R. R News 5. https://cran.r-project.org/doc/Rnews/."

  [[3]]
  [1] "Bivand, R.S., Pebesma, E.J., Gomez-Rubio, V. (2013). Applied spatial data analysis with R, Second edition. Springer, NY. https://asdar-book.org/."

Help?


Solution

  • Using bib2df package:

    library(bibtex)
    library(bib2df)
    
    write.bib(c("base", "sp"), "temp.bib")
    
    x <- bib2df("temp.bib")
    
    apply(x, 1, function(i){
      paste(
        #adding authors and titles
        paste(unlist(i$AUTHOR), collapse = ", "),
        i$TITLE,
        # add other bits here as needed
        sep = ", ")
    })
    
    # [1] "R Core Team, R: A Language and Environment for Statistical Computing"                                        
    # [2] "Edzer J. Pebesma, Roger S. Bivand, Classes and methods for spatial data in {R"                               
    # [3] "Roger S. Bivand, Edzer Pebesma, Virgilio Gomez-Rubio, Applied spatial data analysis with {R}, Second edition"
    

    Note: I am new to bibtex, too. There is also RefManageR package, might be more useful.


    Using RefManageR:

    library(RefManageR)
    
    # read bib file
    x1 <- ReadBib("temp.bib")
    # or convert citations to bibentry object
    x2 <- as.BibEntry(c(citation("base"), citation("sp")))
    

    Both will print as below:

    # [1] R. S. Bivand, E. Pebesma, and V. Gomez-Rubio. _Applied spatial data analysis with R, Second
    # edition_. Springer, NY, 2013. <URL: https://asdar-book.org/>.
    # 
    # [2] E. J. Pebesma and R. S. Bivand. “Classes and methods for spatial data in R”. In: _R News_ 5.2 (Nov.
    #                                                                                                    2005), pp. 9-13. <URL: https://CRAN.R-project.org/doc/Rnews/>.
    # [3] R Core Team. _R: A Language and Environment for Statistical Computing_. R Foundation for
    # Statistical Computing. Vienna, Austria, 2019. <URL: https://www.R-project.org/>.