![](/img/trans.png)
[英]Use roxygen2 to document multiple datasets in a single documentation object
[英]Roxygen2 documentation in a knitr document
假设一个带有代码块的 knitr (rnw) 文件
<<function, include=FALSE>>=
#' A simple function
#'
#' @param foo Variable foo.
#' @param bar Variable bar.
#'
#' @return The product of foo and bar
product<-function(foo, bar) {
return(foo*bar)
}
@
现在假设您要编译文档,并且在生成的 pdf 中将函数文档包含在类似于 Rd 文件的样式中。 那可能吗?
根据@Yihui 提示,我在下面提出了解决方案,您可以根据需要重新定义 latex 命令,并包含 rd2latex= 作为选项。 使用 roxygenize 的 hack 可以做得更好。
\documentclass{article}
\usepackage{framed}
% Redefine latex commands for Rd output
\usepackage{ifthen}
\usepackage{verbatim}
\newcommand{\HeaderA}[3]{}
\newcommand{\code}[1]{\texttt{#1}:}
%\newenvironment{Description}{\iffalse}{\fi}
\newenvironment{Description}%
{%
\ifthenelse{\isundefined{\showtodos}}%
{\expandafter\comment}%
{}%
}%
{%
\ifthenelse{\isundefined{\showtodos}}%
{\expandafter\endcomment}%
{}%
}
\newenvironment{Usage}{}{}
\newenvironment{Arguments}{}{}
\newenvironment{Value}{Returns:}{}
\newenvironment{ldescription}{\begin{itemize}}{\end{itemize}}
\parindent0pt
\begin{document}
<<ini, include=FALSE>>=
library(tools)
library(roxygen2)
library(knitr)
knit_hooks$set(rd2latex = function(before, options, envir) {
if (before) {
# hack: to run roxygenise() folders man, R and a DESC file must be created
basePath <- normalizePath(".")
manPath <- file.path(basePath, "man")
rPath <- file.path(basePath, "R")
fileConn<-file("DESCRIPTION")
writeLines("Package: tmp", fileConn)
close(fileConn)
dir.create(rPath, recursive = TRUE, showWarnings = FALSE)
# save code to an R file
fName<-paste0("chunk_",options$label)
fileConn<-file(paste0("R/",fName,".R") )
writeLines(options$code, fileConn)
close(fileConn)
# generate Rd file
roxygenise()
rdFiles <- list.files("man",full.names = TRUE)
# convert to a latex file which can be included using \input{}
if (options$rd2latex==TRUE) Rd2latex(rdFiles,out=paste0(fName,".tex"))
else Rd2latex(rdFiles,out=paste0(options$rd2latex,".tex"))
# remove working files
unlink(c(manPath,rPath,"DESCRIPTION"), recursive = TRUE, force = TRUE)
}
})
@
\subsection*{Testing}
<<function, include=FALSE, rd2latex='product'>>=
#' A simple function
#'
#' @param foo Variable foo.
#' @param bar Variable bar.
#'
#' @return The product of foo and bar
product<-function(foo, bar) {
return(foo*bar)
}
@
A simple product function is:
\begin{framed}
\input{product.tex}
\end{framed}
\end{document}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.