如何在Rmarkdown中格式化类似帮助的文档

问题描述 投票:1回答:1

我需要为我创建的函数编写一些文档,并且我想模仿R帮助文档中的样式。我的文档将以PDF格式显示,以及R软件包的可下载小插图。准确地说,我想创建一个输出,如下面的dplyr文档中附带的摘录:enter image description here

谁能知道它是如何完成的?它是在Latex没有边框的桌子还是只是一些文字位置调整?在Rmarkdown中模仿它的最佳方法是什么?

r latex r-markdown
1个回答
2
投票

正如我在评论中提到的,我认为这里最好的解决方案是将代码放在一个包中。你似乎对这项任务犹豫不决或恐惧,但它真的很容易,我将简要介绍给你。

假设你有这个功能

example_function <- function(x) {
    return(x * 2)
}

您希望/需要分发的内容,最好是一些文档。这是你如何在R包中相对轻松地做到这一点。我们将添加文档注释Roxygen-style:

#' Example function
#'
#' This is just an example function that multiplies its argument by two.
#'
#' @param x A numeric vector
#'
#' @return A numeric vector equal to \\code{x} multiplied by two.
#' @export
example_function <- function(x) {
    return(x * 2)
}

然后我们会让devtools为我们做一些繁重的工作。首先,我们使用它来设置必要的包结构:

pkg_path <- "/tmp/examplePackage" # Wherever you want your package to be on your machine
devtools::create(pkg_path, rstudio = FALSE)

然后我们将带有上面的示例函数的文件放在为我们创建的包文件夹R/devtools子目录中(在我的例子中,代码现在位于文件/tmp/examplePackage/R/example_function.R中。

然后我们可以简单地运行命令

devtools::document(pkg_path)
# Updating examplePackage documentation
# Loading examplePackage
# Writing NAMESPACE
# Writing example_function.Rd

并且devtools + roxygen2为我们处理所有文档魔术。您现在可以使用devtools::install()为R提供帮助文件:

devtools::install(pkg_path)
?examplePackage::example_function

enter image description here

build_manual创建你提到的花哨的PDF手册:

devtools::build_manual(pkg_path)
# Hmm ... looks like a package
# Creating pdf output from LaTeX ...
# Saving output to ‘/tmp/examplePackage_0.0.0.9000.pdf’ ...
# Done

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.