2

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 @?

Community
  • 1
  • 1
Instanton
  • 399
  • 3
  • 13

1 Answers1

1

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"
PhillipD
  • 1,797
  • 1
  • 13
  • 23
  • Thank you for your answer. The problem with stri_escape_unicode is that it also converts all other special characters such as ' (my LaTeX file is in french so that I have plenty of this). So when I use this function, ' becomes \\' and then the gsub puts @ at the wrong places... – Instanton Nov 07 '16 at 13:25
  • @user3771535 can you add the lines of code where you read the LaTeX file? When I put the string `Let us begin with a note@footnote{This is a note.} and then we will see. D'accord` into a text file and read it using `readLine()` I get the result `[1] "Let us begin with a note\\footnote{This is a note.} and then we will see. D'accord"`. I can directly process this with `gsub('\\',"@",stringFromReadLines,fixed=T)` and get the desired result `[1] "Let us begin with a note@footnote{This is a note.} and then we will see. D'accord"` – PhillipD Nov 07 '16 at 16:03
  • Yeah you are right, I am a fool, when I read it from a file it comes with \\. Thanks a lot !!! – Instanton Nov 08 '16 at 07:16