Editing CommunityData:Knitr

From CommunityData

Warning: You are not logged in. Your IP address will be publicly visible if you make any edits. If you log in or create an account, your edits will be attributed to your username, along with other benefits.

The edit can be undone. Please check the comparison below to verify that this is what you want to do, and then publish the changes below to finish undoing the edit.

Latest revision Your text
Line 1: Line 1:
Knitr is a package that allows you to import dataframes from R and dynamically generate LaTeX tables in your paper. Using knitr is good practice for times when you're working on a paper and make a slight change to your analysis, and need to update every instance where you've reported results.
Knitr is a package that allows you to import dataframes from R and dynamically generate LaTeX tables in your paper. Using knitr is good practice for times when you're working on a paper and make a slight change to your analysis, and need to update every instance where you've reported results.


== Preparation ==
== Preparation ==
Line 5: Line 6:
First, you'd want to create an R script that's organized around every table you want to create in your document. The script should create separate dataframes for every one of them. If your table is going to have rownames, include a vector of rownames in your data frame.  
First, you'd want to create an R script that's organized around every table you want to create in your document. The script should create separate dataframes for every one of them. If your table is going to have rownames, include a vector of rownames in your data frame.  


A data frame for a summary stats table could look something like this, for instance (assuming you've loaded your data in a dataframe called d):
Your data frame could look something like this:


  summary.stats <- data.frame(cbind(
  summary.stats <- data.frame(cbind(c("Var 1", "Var 2", "Var 3"),
                              c("Var 1", "Var 2", "Var 3"),
                               c(min(d$var.1), min(d$var.2), min(d$var.3)),
                               c(min(d$var.1), min(d$var.2), min(d$var.3)),
                               c(median(d$var.1), median(d$var.2), median(d$var.3)),
                               c(median(d$var.1), median(d$var.2), median(d$var.3)),
                               c(max(d$var.1), max(d$var.2), max(d$quality.score))
                               c(max(d$var.1), max(d$var.2), max(d$quality.score))))
                                                  ))
 
Make sure to also include column names for your dataframe:
 
names(summary.stats) <- c("Measures", "Min.", "Median", "Max.")
 
 
Finally, append each table dataframe to a list (i.e. <code>results$summary.stats <- summary.stats</code>), and save this list as an .Rdata file. You'd probably also want to store your entire dataset in the results list (i.e. as <code> results$d </code>).
 
== Latex Preamble ==
 
Save the .Rdata file in the same folder as your tex document. Now, include a preamble like this in your tex file (by all your <code>\usepackage</code> commands):


<<init, echo=FALSE, message=FALSE>>=
knit_hooks$set(document = function(x) {
  sub('\\usepackage[]{color}',
'\\usepackage[usenames,dvipsnames]{color}', x, fixed = TRUE)
})
@


Then, after your <code>\begin{document}</code> command, import your dataset and necessary R packages. You'll need xtable for generating LaTeX tables from Rdata files and ggplot2 for charts and diagrams.
Finally, append each table dataframe to a list, and save this list as an .Rdata file.


  <<import, echo=FALSE, message=FALSE>>=
== Preamble ==
  library(xtable)
  library(ggplot2)
  bold <- function(x) {paste('{\\textbf{',x,'}}', sep ='')}
  gray <- function(x) {paste('{\\textcolor{gray}{',x,'}}', sep ='')}
  wrapify <- function (x) {paste("{", x, "}", sep="")}
  f <- function (x) {formatC(x, format="d", big.mark=',')}
  load("my_data.RData")
  attach(results)
  @


==Using xtable and inserting S expressions==


===xtable===
Each time you want to generate LaTeX code for a table in your document, you need to use knitr to create an R environment and use the xtable package. For instance, printing the summary stats table from the example above would look like this:
<<summary stats, echo=FALSE, message=FALSE, results='asis'>>=
print(xtable(summary.stats,
      caption =
      "Summary statistics.",
      label="table:descriptives", align="llrrr"),
      include.rownames=FALSE)
@
Note that there's a funny thing going on with the <code>align</code> parameter here. R includes some default rownames for dataframes (usually something like X1, X2 etc). Since we have a column that contains our rownames, we need to suppress the default rownames by specifying <code>include.rownames=FALSE</code>. However, even though the <code>summary.stats</code> dataframe contained only four columns, we still need to specify ''five'' column alignments in for the <code>align</code> parameter because the first one corresponds to the default rownames column in the R dataframe. Not specifying the extra column alignment parameter will give you an error.
===Inserting S expressions===
You also will want to have all the instances where you mention things like estimates or quantities from your dataset within the text body to be automatically generated every time you compile your TeX file. In order to do that, every time you mention a number in the text, you need to replace it with an <code>\Sexpr{}</code> command.
For instance, if your text contains a line that says something like "The median of Var 1 is ''x''", then you replace ''x'' with:
\Sexpr{f(median(d$var.1))}
The "f" function here is a formatting function defined in the preamble (see above). This expression also assumes you've appended the study dataframe as <code>d</code> in the <code>results</code> list in the .Rdata file you imported.


== Documentation ==
== Documentation ==
This page provided just the briefest of overviews of how you can use knitr/Sweave/xtable in your TeX document. There's much more documentation available that can help you do more complicated things with these tools. Here are some resources:
* [http://yihui.name/knitr/ Knitr documentation]
* [http://kbroman.org/knitr_knutshell/ Knitr in a knutshell tutorials]
* [https://cran.r-project.org/web/packages/xtable/xtable.pdf xtable documentation]
* [https://cran.r-project.org/web/packages/xtable/vignettes/xtableGallery.pdf xtable gallery]
** This is super useful for figuring out ways to use xtable to make various kinds of tables
Please note that all contributions to CommunityData are considered to be released under the Attribution-Share Alike 3.0 Unported (see CommunityData:Copyrights for details). If you do not want your writing to be edited mercilessly and redistributed at will, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource. Do not submit copyrighted work without permission!

To protect the wiki against automated edit spam, we kindly ask you to solve the following CAPTCHA:

Cancel Editing help (opens in new window)