Extracting Code of R function to be used in knitr with controled width
We can use formatR::usage(lm)
to get the arguments of lm
function and can use the following command to redirect the output to knitr
:
<<test, code=formatR::usage(lm), eval=FALSE>>=
@
I wonder if there is such function to get the lm
function code to redirect to knitr
.
Edited
Got the code of lm
function to be used in knitr
using the following code (as suggested by @JoshO'Brien):
<<test, code=lm, eval=FALSE>>=
@
But could not figure out how to control the width
of knitr
output.
To embed a 'tidy' definition of some function see Yihui's self-explanatory existing code,
<<insert-fun, echo=FALSE>>=
insert_fun = function(name) {
read_chunk(lines = capture.output(dump(name, '')), labels = paste(name, 'source', sep = '-'))
}
@
<<insert-lm, echo=FALSE>>=
insert_fun('lm')
@
<<lm-source, eval=FALSE, tidy=TRUE, tidy.opts=list(width.cutoff=30)>>=
@
Example Rnw and Rmd Gist
When output is going to latex, there are sometimes have issues with getting line breaks to stay within the page margins. Its a known issue with multiple fixes that have various drawbacks. Like this one where you get the full function within the margins but without the pretty coloring... It is all a matter of trade-offs and/or effort you put into a solution. :)
documentclass{article}
usepackage{listings}
usepackage{inconsolata}
<<echo=FALSE>>=
options(width=60)
listing <- function(x, options) {
paste("begin{lstlisting}[language=R,basicstyle=ttfamily,breaklines=true]n",
x, "end{lstlisting}n", sep = "")
}
knit_hooks$set(source=listing, output=listing)
insert_fun = function(name) {
read_chunk(lines = capture.output(dump(name, '')), labels = paste(name, 'source', sep = '-'))
}
@
<<insert-lm, echo=FALSE>>=
insert_fun('lm')
@
begin{document}
<<lm-source, eval=FALSE, tidy=TRUE, tidy.opts=list(width.cutoff=50)>>=
@
end{document}
链接地址: http://www.djcxy.com/p/26848.html
上一篇: 确定鼠标是否在窗外
下一篇: 提取R函数的代码用于控制宽度的针织物