user3771535 user3771535 - 1 month ago 21
LaTeX Question

Reading LaTeX file in R: how to get get of single backslash

I am trying to read with R a LaTeX file with functions starting with the character \ . I would like to get rid of these backslashes (I would like to replace them by @ before treating the content of the file itself). I have seen some questions posted here (like this or this), but none of the proposed solution seems to work.

When I try

paragraph = "Let us begin with a note\footnote{This is a note.} and then we will see"
gsub("\\","@",paragraph,fixed=T)


I obtain

[1] "Let us begin with a note\footnote{This is a note.} and then we will see"


I understand that paragraph does not contain a real backslash as R thinks that \f is a character. But I do not know how to deal with it. the paragraph variable is in fact red from a file using ReadLines: maybe is there a function allowing to read \ as \?

How to perform this substitution of \ to @?

Answer

You can use the stringi package to escape the \ before you pass it to gsub.

library(stringi)
paragraph <-  stri_escape_unicode("Let us begin with a note\footnote{This is a note.} and then we will see")
gsub('\\',"@",paragraph,fixed=T)

[1] "Let us begin with a note@footnote{This is a note.} and then we will see"