首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >document文档中的Roxygen2文档

document文档中的Roxygen2文档
EN

Stack Overflow用户
提问于 2015-10-02 20:20:44
回答 1查看 289关注 0票数 2

假设一个包含代码块的针织(rnw)文件

代码语言:javascript
复制
<<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文件的样式包含函数文档。这有可能吗?

EN

回答 1

Stack Overflow用户

发布于 2015-10-30 19:34:16

基于@Yihui的提示,我提出了下面的解决方案,您可以根据自己的喜好重新定义latex命令,并将rd2latex=作为一个选项。使用roxygenize的黑客攻击可以做得更好。

代码语言:javascript
复制
\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}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32907054

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档