Reputation: 13792
I regularly embed R code into Rnw files and use knitr
to convert the Rnw file to a tex file and then pdf. The upside of this approach is that is increases reproducibility. The downside is that it interrupts the flow of the writing process.
For example, assume the following is part of the results section of a research paper:
I compared the means of group A and group B. The mean of group A was
\Sexpr{mean(groupA)}
. The mean of group B was\Sexpr{mean(groupB)}
. (the following couple of sentences then place the two means in context, interpret the value of the two means and explain the relevance of the size of their difference)
In order to place the means in context, interpret their value and explain the relevance of their difference, I need to be able to see the actual value of each mean. But I cannot see the value of each mean without running knitr
to convert to tex and then pdf, which fragments and inhibits the flow of the writing process.
Do people use any methods that allow R code to run within the Rnw file. In the above example, is there a way of showing of the value of each mean within the Rnw file, such that the flow of writing isn't interrupted? Or are there any workarounds?
Upvotes: 4
Views: 1746
Reputation: 193517
If you use RStudio, you could do something like the following:
\documentclass{article}
\begin{document}
<<echo = FALSE, eval = TRUE, results='hide'>>=
# This is a code chunk that I want to ealuate and store variables in.
# I can "ctrl + enter" in here and actually run the calculations in
# the console in RStudio.
set.seed(1)
A <- sample(300, 30)
B <- sample(200, 40)
mA <- mean(A);mA
mB <- mean(B);mB
@
I compared the means of group A and group B. The mean of group A was
\Sexpr{mA}. The mean of group B was \Sexpr{mB}.
\end{document}
While composing the document, you can actually run the chunk (there's even a button for "Run Current Chunk" -- Ctrl + Alt + C) or just run specific lines using Ctrl + Enter. The output would be shown in the console, allowing you to compare the values before writing your sentence, but without having to fully compile your document.
Upvotes: 3