R 中的函数注释约定

问题描述 投票:0回答:4

我对 R 相当陌生,我一直在脚本文件中定义一些我自己的函数。我打算让其他人稍后重用它们,但我找不到任何有关 R 函数注释约定的指南。有什么办法可以让

help("my_function_name")
显示一些帮助吗?如果没有,我是否只需在脚本文件中记录该函数,以便有人必须打印(或打开脚本的源代码)才能查看注释?

谢谢,

哈米

r conventions comments
4个回答
22
投票

于 2019 年 12 月更新此问题,因为 R 宇宙自 2011 年最初编写时以来已经发生了变化

我推荐的资源现在是http://r-pkgs.had.co.nz/

原始答案(链接大多已过时)

记录您的函数并使其可供其他人访问的规范方法是制作一个包。为了使您的包通过构建检查,您必须为每个函数/数据集提供足够详细的帮助文件。

查看 http://cran.r-project.org/doc/manuals/R-exts.html#Creating-R-packages

Rob J Hyndman 的这篇博客文章非常有用,也是我最容易理解的博客文章之一:http://robjhyndman.com/researchtips/building-r-packages-for-windows/

我最近开始使用 roxygen 来协助制作和编译软件包:http://roxygen.org/

有很多好的资源和人员可以在您有疑问时提供帮助!


19
投票

您可以研究的另一个(也是较低键)替代方案是

comment()
attr()
函数,用于向函数添加一些元数据。这是一个简单而愚蠢的例子:

FOO <- function(x,y) {
 x + y 
}

attr(FOO, "comment") <- "FOO performs simple addition"

#This can be arbitrary. "comment" is special. see ?comment for details.
attr(FOO, "help") <- "FOO expects two numbers, and it will add them together"

然后您可以使用

FOO
:
 查看与 
attributes()

相关的所有内容
> attributes(FOO)
$source
[1] "function(x,y) {" " x + y "         "}"              

$comment
[1] "FOO performs simple addition"

$help
[1] "FOO expects two numbers, and it will add them together"

或提取特定部分:

> attr(FOO, "help")
[1] "FOO expects two numbers, and it will add them together"
attr(FOO, "comment")
[1] "FOO performs simple addition"

如果是评论,请使用

comment()
:

> comment(FOO)
[1] "FOO performs simple addition"

从长远来看,编写自己的包几乎肯定是值得的管理费用和时间投资,但如果由于某种原因在短期内不切实际 - 这是另一种选择。


7
投票

您必须将函数放入包中(这使得移植函数非常容易)。我不久前写了一篇关于它的短文,其中包含一些扩展主题的相关文档的链接(我希望它们仍然有效)。

您可以使用 roxygeninlinedocs“即时”生成帮助文件。


0
投票

如果您不构建包,则可以使用

docstring
包,它提供与 Python 文档字符串类似的功能。

libaray(docstrin)
library(docstring)

square <- function(x){

    #' Square a number
    #'
    #' Calculates the square of the input
    #'
    #' @param x the input to be squared

    return(x^2)
}

您可以拨打

?square
查看评论。 输出

本教程可能会有所帮助。

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