0

I want to print a chunk of latex code using R. I've previously used cat() to do this, my problem is that it quickly becomes a cumbersome task when I have a large body of text including tables written in latex as I have to include additional backslashes in R. i.e., if I want a tex-file with the following:

\begin{document}

I would need to write something like

cat("\\begin{document}", file= test.tex, append = T, sep="\n")

in R.

I've also tried:

sink("test.tex")
print("\begin{document}", quote = F)
sink()

which almost gives me the desired result except for the fact that it prints row numbers in front of the text, more specifically it prints:

[1] \begin{document}

Is there a way to write plain latex code in R and get it to work properly without adding additional backslashes or row numbers? I know there are more sophisticated solutions using sweave, knitr, Rmarkdown but would prefer to a solution using print/writeLines/cat, etc.

Tordir
  • 191
  • 6
  • If you get `[1] \begin{document}` with an editor supporting replacement of regular expressions, like RStudio, it is quite easy to remove all substrings as `[1] ` – iago Oct 01 '19 at 12:54

1 Answers1

1

If you are pasting text into the console or piping a file into R from the command line, you can use something like this:

latex <- scan(what = character())
\begin{document}
\end{document}

writeLines(latex, "test.tex")

where the blank line tells scan() to stop reading. However, if you put those lines in a file and source() it, you'll get an error, because it's not all syntactically correct R code.

You're definitely better off to use knitr with .Rnw input.

user2554330
  • 37,248
  • 4
  • 43
  • 90