How to interpret R within Latex - not R markdown

Cool trick I recently learned to interpret R within Latex. This means you can print R objects in a sentence and have it not look like markdown. This can be a cool time saving trick if you only need to do some rudimentary calculations for your document (e.g. summary statistic calculation).

Instructions

  1. First rename the suffix of your Latex file name as .Rtex (this is how Overleaf knows to use R, you may or may not need to do this when compiling on your own desktop. Please feel free to add to this description).
  2. Add R code to your Latex file like this:



    <<echo=FALSE>>=
    dat <- read.csv("./data/publication_data.csv")
    for(i in 14:55){
    dat[,i] <- gsub("\n","",dat[,i])
    }
    uniq_studies <- length(unique(dat$Citation))
    uniq_hosts <- length(unique(dat$Host_taxon))

    @

    NOTE: the code I use here is copied from something I am working on and is not a reproducible example. But you get the idea.
  3. The <<echo=FALSE>>= bit keeps your code from printing (though if you have code that would print output to STDIN (the screen), that still happens). The "@" ends the code chunk.
  4. Next, you can call objects within your text using $\Sexpr{yourcode}$. For instance: "Our survey immediately highlighted the dramatic breadth of the endophyte biodiversity literature, as we surveyed $\Sexpr{uniq_studies}$ studies."

  5. This renders as "Our survey immediately highlighted the dramatic breadth of the endophyte biodiversity literature, as we surveyed 592 studies."
  6. You can put code within \Sexpr{} as well, but I have found it cleaner to split the R code out, save objects, and just call the objects in the text. This helps me read the Latex code but is not strictly necessary.