简体   繁体   English

将R代码的输出插入Rnw文件

[英]Insert output of R code into an Rnw file

I regularly embed R code into Rnw files and use knitr to convert the Rnw file to a tex file and then pdf. 我经常将R代码嵌入到Rnw文件中,并使用knitr将Rnw文件转换为tex文件,然后转换为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)} . 我比较了A组和B组的平均值.A组的平均值是\\Sexpr{mean(groupA)} The mean of group B was \\Sexpr{mean(groupB)} . B组的平均值为\\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. 但是我没有看到每个意思的价值,如果没有运行knitr转换为tex然后转换为pdf,这会破坏和抑制写入过程的流程。

Do people use any methods that allow R code to run within the Rnw file. 人们是否使用任何允许R代码在Rnw文件中运行的方法。 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? 在上面的例子中,是否有一种方法可以显示Rnw文件中每个均值的值,从而不会中断写入流程? Or are there any workarounds? 或者有任何变通方法吗?

If you use RStudio, you could do something like the following: 如果您使用RStudio,您可以执行以下操作:

\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 . 在编写文档时,您实际上可以运行块(甚至可以使用“运行当前块”按钮 - Ctrl + Alt + C )或使用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. 输出将显示在控制台中,允许您在编写句子之前比较值,但无需完全编译文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM