Mastering R Programming: Incorporating R code into a Sweave document

Matthew RichardsonProduct Coordinator
Published:
Updated:
This article will show, step by step, how to integrate R code into a R Sweave document
I am writing this article as a continuation to my previous article, which introduced how to create a beautiful looking document with R Sweave.  However, the presentable look that Sweave documents offer is only half their power!  Another very important feature is incorporating R code directly into the script. That way when it compiles, you can have a presentable way to display your data!
 
To begin, create a Sweave document and populate it with the same sort of information as we did in the last article.  For reference I have included the code outline below:
\documentclass{article}
                       
                      \title {Using \LaTeX with R}
                      \author {Matthew Richardson\\
                      Written for Experts Exchange
                      }
                       
                      \begin{document}
                      \SweaveOpts{concordance=TRUE}
                       
                      \maketitle
                       
                      \section*{Incorporating R code}
                       
                      \end{document}
                      

Open in new window


Now, in order to be able to include R code, you need to designate a special block so Sweave knows you mean it to utilize R’s capabilities.  This will be marked with:
<<>>=
                        (code)
                      @
                      

Open in new window

You want to include this in the body of your script (see below)
Screen-Shot-2015-09-16-at-10.03.23-A.pngI know it looks odd at first.  You will know if R studio considers this block of code because it will become shaded on your script file and look like this:
Screen-Shot-2015-09-25-at-1.01.56-PM.pngWithin the opposite facing inequalities is your location to put arguments you want the code to follow.  To list some of the most frequently used:
 
  1. Echo = FALSE if you do not want the code to be generated in your document
Echo = TRUE if you would like the code for the output to display
  1. Results = hide if you want the output from the code to be hidden
Results = tex if you want the output of the code to display in LaTeX format
  1. Fig = TRUE to display figures from a line of code
  2. Label = fig1 (or whatever you want to name your figure)
 
*To list multiple, make sure to just separate the arguments with a comma (,) for example:
label=fig1,fig=TRUE,echo=FALSE
                      

Open in new window


So lets do an example.  Say I wanted to write a LaTeX article about the popular book series A Song of Ice and Fire.  And lets say somewhere in that article I wanted to include the table found on the series Wikipedia page under Publishing History.  Well one step would be to make the table myself.  Or I could use the power of R to incorporate the information!  (See below)

<<echo=FALSE, results=hide>>=
                      library(XML)
                      library(httr)
                      url <- GET("http://en.wikipedia.org/wiki/A_Song_of_Ice_and_Fire")
                      table <- readHTMLTable(rawToChar(url$content), stringsAsFactors = F)
                      str(table)
                      table[[2]]
                      books <- as.data.frame(table[[2]])[,-1]
                      names(books) <- c("Title","Pages","Chapters","Audio Length","U.S. Release")
                      books[,2] <- c(704,768,992,753,1056,NA,NA)
                      @
                       
                      <<results=tex>>=
                      library(xtable)
                      xtable(books)
                      @
                      

Open in new window


I separated the two blocks of code to display that you can continue on with a different section of code with different arguments.  This would display like this:
  Screen-Shot-2015-09-25-at-1.17.26-PM.png 
And then to incorporate a figure I would just write:
<<label=fig1,fig=TRUE,echo=FALSE>>=
                      plot(1:7,books[,2],xlim=c(1,5),xlab="Book Number",ylab="Number of Pages",main="Number of Pages per Book")
                      @
                      

Open in new window


And I get a perfect figure created when I compile my document automatically!
 
Screen-Shot-2015-09-25-at-1.19.01-PM.png 
Great isn’t it!?
 
I will leave you to experiment with any R code that you want to use, but I can attest to the fact that utilizing this powerful functionality of R and R Studio will make any dull LaTeX articles come to life with a lot less effort than before!
 
The only issue I would normally run into when I was first learning would be formatting.  There are a lot of tricks and work-arounds to fitting a graphic or plot on a page within the margins.  If you run into anything like this, or have follow-up questions, please don’t hesitate to leave a comment! I would love to help!
3
2,213 Views

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.