简体   繁体   English

如何在Knitr块中使用变量R代码?

[英]How to use variable R code in a Knitr chunk?

I want to demonstrate use of a piece of R code. 我想演示一段R代码的用法。 But I want the code to be variable itself. 但是我希望代码本身是可变的。

Example two tasks: 示例两个任务:

  1. Randomly select two variables from a data frame and add those columns. 从数据框中随机选择两个变量,然后添加这些列。
  2. Randomly select a set of numbers and calculate their median. 随机选择一组数字并计算其中位数。

Defined data frame: 定义的数据框:

<<echo=FALSE,results='hide'>>=
df <- data.frame(x1 = sample(1:5, 3), x2 = sample(1:5, 3), 
                 x3 = sample(1:5, 3), x4 = sample(1:5, 3))
@

This is how the final output code should look like on the presentation: 这是最终输出代码在演示文稿上的样子:

<<foo_chunk,results='markup',echo=TRUE>>=
# You can add two columns by:
s = df$x1 + df$x3
# The median:
median(c(2, 31, 14, 5, 6))
@

在此处输入图片说明

Currently, I'm achieving this by the following code. 目前,我正在通过以下代码实现这一目标。 But I cannot utilize the nice code highlighting available for knitr code chunks: 但是我无法利用适用于knitr代码块的漂亮代码突出显示:

<<results='asis',echo=FALSE>>=
cn <- sample(colnames(df), 2)
cat("\\# You can add two columns by:\n\n")
cat("s = df\\$", cn[1], " + df\\$", cn[2], "\n\n", sep = "")
x <- sample(1:100, 5)
cat("\\# The median:\n\n")
cat("median(c(", paste0(x, collapse = ", "), "))\n\n", sep = "")
cat("\\#\\#", median(x), "\n")
@

UPDATE: 更新:

I found a way to capture output similar to foo_chunk above: 我找到了一种捕获输出的方法,类似于上面的foo_chunk

<<echo=FALSE,results='hide'>>=
df <- data.frame(x1 = sample(1:5, 3), x2 = sample(1:5, 3),
                 x3 = sample(1:5, 3), x4 = sample(1:5, 3))

foo <- function(cn = colnames(df), 
                x = sample(1:100, 5)) {
  return(c(
    paste0("# You can add two columns by:"),
    paste0("s = df$", cn[1], " + df$", cn[2]),
    paste0("# The Median:"),
    paste0("median(c(", paste0(x, collapse = ", "), "))")
    ))
}
@

<<code=capture.output(cat(foo(), sep="\n"))>>= 
@

This code will give the output without any side effects (ie creating a new temporary file like "foo.R"). 此代码将给输出无任何副作用(即创建一个新的临时文件,如“ foo.R”)。

Any other solution that is more efficient will be greatly appreciated. 任何其他更有效的解决方案将不胜感激。

You might be able to do this by calling the hooks defined by knitr::render_latex() directly (see https://yihui.name/knitr/hooks/ ), but it looks tricky. 您可能可以通过直接调用knitr::render_latex()定义的钩子来做到这一点(请参阅https://yihui.name/knitr/hooks/ ),但这看起来很棘手。 Why not just write the variable code into a separate file, and include it? 为什么不只将变量代码写到一个单独的文件中并包含它呢?

For example, 例如,

\documentclass{article}

\begin{document}

<<echo=FALSE,results='hide'>>=
df <- data.frame(x1 = sample(1:5, 3), x2 = sample(1:5, 3), 
                 x3 = sample(1:5, 3), x4 = sample(1:5, 3))
@


<<echo=FALSE>>=
cn <- sample(colnames(df), 2)
x <- sample(1:100, 5)
code <- paste0(
"<<echo=TRUE>>=
# You can add two columns by
s = df$", cn[1], " + df$", cn[2], "
# The median:
median(c(", paste0(x, collapse = ", "), "))
@")
writeLines(code, "sampleCode.Rnw")
@

<<child="sampleCode.Rnw">>=
@

\end{document}

This produces the output 这产生输出

在此处输入图片说明

Edited to add: 编辑添加:

Using the code= addition to the question makes this even simpler: 在问题中使用code=加法使此操作变得更加简单:

\documentclass{article}

\begin{document}

<<echo=FALSE,results='hide'>>=
df <- data.frame(x1 = sample(1:5, 3), x2 = sample(1:5, 3), 
                 x3 = sample(1:5, 3), x4 = sample(1:5, 3))

cn <- sample(colnames(df), 2)
x <- sample(1:100, 5)
code <- paste0(
"# You can add two columns by
s = df$", cn[1], " + df$", cn[2], "
# The median:
median(c(", paste0(x, collapse = ", "), "))")
@

<<code = code>>=
@

\end{document}

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

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