有一种明智的方法来在R中执行类似文档字符串的操作吗? [英] Is there a sensible way to do something like docstrings in R?

查看:42
本文介绍了有一种明智的方法来在R中执行类似文档字符串的操作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不仅仅是编码风格的问题.如果您了解python(我也认为Ruby也有类似的东西),则您可以在函数中使用docstring,以便您可以通过发出"help"命令轻松获得该字符串.例如:

This is not just a coding style question. If you know python (and I think also Ruby has something like this), you can have a docstring in a function, such that you can readily get that string by issuing a "help" command. e.g.:

def something(t=None):
    '''Do something, perhaps to t

    t : a thing
        You may not want to do this
    '''
    if t is not None:
        return t ** 2
    else:
        return 'Or maybe not'

然后 help(something)返回以下内容:

Help on function something in module __main__:

something(t=None)
    Do something, perhaps to t

    t : a thing
        You may not want to do this

R中的工作方式,您可以获取已定义代码段的全文,因此可以看到注释(包括函数开头的注释),但这可能需要大量滚动和可视过滤.有什么更好的方法吗?

The way things work in R, you can get the full text of the defined code snippet, so you could see comments (including those at the beginning of the function), but that can be a lot of scrolling and visual filtering. Is there any better way?

推荐答案

我最近编写了一个软件包来完成此任务. docstring 包允许用户在其记录的功能内以roxygen样式注释的形式编写其文档.例如,一个可以做

I recently wrote a package to do just this task. The docstring package allows one to write their documentation as roxygen style comments within the function they are documenting. For example one could do

square <- function(x){
    #' Square a number

    return(x^2)
}

然后要查看文档,请调用docstring函数

and then to view the documentation either call the docstring function

docstring(square)

还是使用内置的?支持并执行

or use the built in ? support and do

?square

注释可以是上面显示的单个块,也可以是完全roxygen样式的,以利用提供的某些关键字

The comments can either be a single chunk like shown above or fully roxygen style to take advantage of some of the keywords provided

square <- function(x){

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

    return(x^2)
}

现在在CRAN上: https://cran.r-project.org/package=docstring ,因此您可以使用

This is on CRAN now: https://cran.r-project.org/package=docstring so you can just install using

install.packages("docstring")

或者如果您想要最新的开发版本,则可以从github安装:

or if you want the latest development version you can install from github:

library(devtools)
install_github("dasonk/docstring")

这篇关于有一种明智的方法来在R中执行类似文档字符串的操作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆