Splitting knitr Chunk code and output into two different knitrouts

烈酒焚心 提交于 2019-12-04 04:46:53

You'll have to play around with formatting, but you can achieve this by modifying the source code hook. What I show below is actually a very simple modification of the basic render_latex hook that adds \\noindent\\textbf{Code:} before the code and \\noindent\\textbf{Output:} after it:

\documentclass{article} 
\begin{document}

<<setup, include=FALSE>>=
knit_hooks$set(
source = function(x, options) {
      x = knitr:::hilight_source(x, 'latex', options)
      if (options$highlight) {
        if (options$engine == 'R' || x[1] != '\\noindent') {
          paste(c('\\noindent\\textbf{Code:}\\begin{alltt}', x, '\\end{alltt}', '','\\noindent\\textbf{Output:}'),
                collapse = '\n')
        } else {
          if ((n <- length(x)) > 5) x[n - 3] = sub('\\\\\\\\$', '', x[n - 3])
          paste(c('\\noindent\\textbf{Code:}',x, '','\\noindent\\textbf{Output:}'),
                collapse = '\n')
        }
      } else .verb.hook(x)
    }
)
@

Here's your first chunk.

<<chunk1, results = "hold" >>=
1:100
args(lm)
@ 

And here's another.

<<chunk2, results = "hold">>=
1:5
6:10
@ 

That seems to be it.

\end{document}

Here's the result:

Thanks to a slight modification suggested by @mrbcuda in comments means you can separate the code and output frames:

Here's the modification of the setup chunk:

<<setup, include=FALSE>>=
knit_hooks$set(
source = function(x, options) {
      x = knitr:::hilight_source(x, 'latex', options)
      if (options$highlight) {
        if (options$engine == 'R' || x[1] != '\\noindent') {
          paste(c('\\noindent\\textbf{Code:}\\begin{alltt}', x, '\\end{alltt}', '','\\end{kframe}\\begin{kframe}\\noindent\\textbf{Output:}'),
                collapse = '\n')
        } else {
          if ((n <- length(x)) > 5) x[n - 3] = sub('\\\\\\\\$', '', x[n - 3])
          paste(c('\\noindent\\textbf{Code:}',x, '','\\noindent\\textbf{Output:}'),
                collapse = '\n')
        }
      } else .verb.hook(x)
    }
)
@

And the resulting output:

I'm unsure exactly what you want to do, but does this give you the desired output? I split the task into two chunks. First, I put off the evaluation of the first chunk and only print the output in the second.

\documentclass{article}
\begin{document}

\subsection{Code}
<<label=chunk1, eval=FALSE>>=
1:10
args(lm)
@

\subsection{Output}
<<label=chunk2, echo=FALSE>>=
<<chunk1>>
@

\end{document}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!