3

I am trying to get a STATA macro or an R variable into Latex. This is relatively straightforward with R markdown, but I'm hoping for a pure TeX solution. e.g. say I have a document that says

Our model predicts [x] number of hamburgers will be consumed by aliens.

and a STATA do file or an R file that says

x <- 10000

or

local x 10000

How do I get latex to be able to update that number each time I get new data? For figures, it's relatively simple, because I can import a code block with the figure, but what about for just numbers?

Apologies if this has been asked already--I've tried searching to no success, probably because I don't know the correct jargon and search terms to use.

Thanks for your help!

ShreevatsaR
  • 45,428
  • 10
  • 117
  • 149
Daycent
  • 225

2 Answers2

2

You can write that number to a file, say, alien_hamburgers.txt, and then read that file into a macro via catchfile's \CatchFileDef{\alienhamburgers}{alien_hamburgers.txt}{} that you can then use in your (La)TeX file:

Our model predicts \alienhamburgers{} number of hamburgers will be consumed by aliens.

Another option would be to write the TeX assignment into a file specifically from R, so in alien_hamburgers.tex would contain

\newcommand{\alienhamburgers}{10000}

that you can just \input{alien_hamburgers} within the preamble. This would give you access to \alienhamburgers within the document.

Werner
  • 603,163
0

You can include the R code to obtain the variable in the same LaTeX file, without the need of auxiliary files, as easy as in Rmarkdown. You only have to change the .tex extension to .Rnw in Rstudio (or .Rtex in Overleaf) to allow to the editor to know that it must be processed first by R, and then compiled to PDF by a latex engine. The MWE:

\documentclass{article}
\begin{document}
<<data,echo=F>>=
x <-mean(c(500,1500)) 
@
Our model predicts \Sexpr{x} hamburgers will be consumed by aliens.
\end{document}
Fran
  • 80,769