Search code examples
rbibtexmendeley

Writing .bib file from R with abstracts


I have .bib file (downloaded from web of science) and I want to import it into R, replace all instances of "in light of" with "CONSIDERING", and export it as a .bib file. I have not been able to find a function that can write my data back to a .bib file. WriteBib does not work because refs is a "pairlist" object, not "bibentry". Any advice on how to export a .bib file that can be imported into Mendeley? thanks for your help!

here is the code:

library(bibtex)
library(RefManageR)

refs = do_read_bib("/Users/CarrieAnn/Downloads/savedrecs (1).bib", encoding = "unknown", srcfile)

for (i in 1:length(refs)) {
  refs[[i]] = gsub("in light of", "CONSIDERING", refs[[i]])
}

Solution

  • I think your easiest option is to treat the .bib file like a normal text file. Try this:

    raw_text  <- readLines("example.bib")
    new_text  <- gsub("in light of", "CONSIDERING", raw_text)
    writeLines(new_text, con="new_example.bib")
    

    Contents of example.bib:

    %  a sample bibliography file
    %  
    
    @article{small,
    author = {Doe, John},
    title = {A small paper},
    journal = {The journal of small papers},
    year = 1997,
    volume = {-1},
    note = {in light of recent events},
    }
    
    @article{big,
    author = {Smith, Jane},
    title = {A big paper},
    journal = {The journal of big papers},
    year = 7991,
    volume = {MCMXCVII},
    note = {in light of what happened},
    }
    

    Output of new_example.bib:

    %  a sample bibliography file
    %  
    
    @article{small,
    author = {Doe, John},
    title = {A small paper},
    journal = {The journal of small papers},
    year = 1997,
    volume = {-1},
    note = {CONSIDERING recent events},
    }
    
    @article{big,
    author = {Smith, Jane},
    title = {A big paper},
    journal = {The journal of big papers},
    year = 7991,
    volume = {MCMXCVII},
    note = {CONSIDERING what happened},
    }
    

    A bit of explanation:
    BibEntry objects have non-standard internals and are hard to work with, outside of the functionality provided in the RefManageR package. As soon as you unclass or reduce a BibEntry object to a list, it becomes difficult to put back into a bib format, due to the object's required mix of fields and attributes. (And to make matters worse, bibtex and RefManageR don't have exactly the same internal structure, so it's hard to convert from one context to the other.)