简体   繁体   中英

How to use variable R code in a Knitr chunk?

I want to demonstrate use of a piece of R code. 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:

<<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:

<<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").

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. 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:

\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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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