34

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'

Then help(something) returns the following:

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

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?

5
  • And the next question: is there a way to automatically convert these docstrings to man pages when building a package?
    – naught101
    Jul 8, 2014 at 2:53
  • @naught101 I just put my docstring package on CRAN. It doesn't have the ability to automatically convert the docstrings to man pages... yet. The goal is for the next minor release to contain a helper function to convert input scripts to the appropriate format for roxygen2 (and generate the Rd files if everything is in package format).
    – Dason
    Mar 24, 2017 at 20:41
  • Weird that mods closed this as an opinion based question, and it has nearly 30 upvotes.
    – jbuddy_13
    Nov 2, 2020 at 16:46
  • Stack Overflow sites, just like Wikipedia, etc. developed a culture to deal with problems. It's opinionated and not always the most useful approach for everyone and all cases, but it's better than total chaos or moderation at the whim of some high ranked user!
    – Dav Clark
    Nov 26, 2020 at 19:04
  • @jbuddy_13 I don't actually think it was mods that closed it. Just looks like other users with voting rights. But looking through those users it doesn't look like any of them are R or Python users or at least that isn't anywhere to be found in their main tags. I disagree with the closing of it.
    – Dason
    Jun 30, 2022 at 15:52

6 Answers 6

23

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)
}

and then to view the documentation either call the docstring function

docstring(square)

or use the built in ? support and do

?square

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)
}

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

install.packages("docstring")

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

library(devtools)
install_github("dasonk/docstring")
3
  • 2
    This is very cool. Will it still Roxygenize? Mar 13, 2017 at 18:11
  • 2
    @Gregor Well the comments in "docstring" form live inside the function so if you ran roxygenize on a file where you have your documentation stored as docstrings it won't roxygenize to Rd files. Ideally though you're just using docstrings for scripts that you haven't converted to package form. But having the documentation like this should make an easy transition since you should be able to just move the docstring outside the function and then it will be ready to run roxygenize. I plan on making a helper function that will do this conversion for you if supplied a script.
    – Dason
    Mar 13, 2017 at 20:09
  • 3
    @Gregor Version 1.0.0 on CRAN doesn't yet have that ability but I'm definitely planning it for the next release.
    – Dason
    Mar 24, 2017 at 20:42
12

You can add any attributes you like to R objects, including function. So something like

describe <- function(obj) attr(obj, "help")
foo <- function(t=NULL) ifelse(!is.null(t), t^2, "Or maybe not")
attr(foo, "help") <- "Here is the help message"

produces more or less the desired output

> foo(2)
[1] 4
> foo()
[1] "Or maybe not"
> describe(foo)
[1] "Here is the help message"
1
  • 4
    I like the fact that this is super lightweight, and could in theory be used on anything. Only downside is that it's not in the ideal place in the actual code...
    – Dav Clark
    May 10, 2011 at 5:15
11

Sort-of -- look at the roxygen2 package on CRAN (vignette here). You write a declarative header, and among other things a help page is created for you when you 'roxygen-ize' your sources.

It may not be the easiest package to use, see here on SO for questions pertaining to it as well as its mailing list. But it probably is the closest match.

2
  • 1
    This reminded me of the integration of R with Sphynx in the openmx project: openmx.psyc.virginia.edu/thread/65 (not really authoritative). All of that's a bit more overhead than the sort of quick and dirty something for the undergrads, though... Sphynx is nowhere near as nice for R as for python (as far as I can tell).
    – Dav Clark
    May 10, 2011 at 5:38
  • This is very easy to do using RStudio: You add a header to the function (e.g. "#' Here is the help message"), then press CTRL+SHIFT+D, then CTRL+SHIFT+B to build the package. Then type "?something" to see the help.
    – jciloa
    Apr 13, 2016 at 12:44
9

RStudio helps you to create documentation quite easily. See their documentation for more information.

2
  • 2
    This is the most sensible way, as it is standard, and gives excellent results easily. Perhaps you could add a little more detail so that people can see how easy it is?
    – jciloa
    Apr 13, 2016 at 12:42
  • 1
    Note that this has nothing to do with RStudio really so you could use this no matter what you're using to interact with R.
    – Dason
    Dec 28, 2017 at 12:39
4

I had another idea as I'm finally wrapping my head around the fact that "R is a (very poor) LISP". Specifically, you can get access to the source code (usually) using the deparse command. So, this function would be a start towards defining your own custom source-code parsing help function:

docstr <- function(my.fun) {
    # Comments are not retained
    # So, we can put extra stuff here we don't want
    # our docstr users to see
    'This is a docstring that will be printed with extra whitespace and quotes'
    orig.code.ish <- deparse(my.fun)

    print(orig.code.ish[3])
}

docstr(docstr)

The above illustrates that deparse really does deparse, and is different from what you'd print at the REPL prompt if you typed docstr: quotes are changed to (default) double-quotes, opening curly brace gets moved to the second line, and blank lines (including comments) are removed. This actually helps a lot if you want to design a robust function. Would be trivial to look for e.g., opening and closing quotes down through the first line that doesn't start with a quote.

Another way to do it would be to get the list of call objects that make up the body list with body(docstr). The string would be in body(docstr)[[2]]. I have to admit that I'm a bit out of my depth here, as I don't fully understand the return value of body, and don't know where to find documentation! In particular, note that body(docstr)[2] returns an object of type and mode 'call'.

This latter approach seems much more LISPy. I'd love to hear other's thoughts on the general idea, or have pointers to actual language reference materials for this!

3

The new reference class system has something very similar to docstrings for documenting methods of a class. Here is an example:

Something <- setRefClass("Something",
                         methods=list(
                           something=function(t=NULL) {
                             "Do something, perhaps to t
    t : a thing
        You may not want to do this
"
                             if(!is.null(t))
                               t^2
                             else
                               "Or maybe not"
                           }
                           ))


a <- Something$new()
a$something(2)
a$something()

Something$help("something") ## to see help page
2
  • 1
    I had no idea about this. But, given that the docs for setRefClass say that the API is subject to change as of R 2.12, I'm a little hesitant to get into that. For some reason, I've never gotten into object oriented R... I think the barrier is just too high, and before I get to where that'd be worth it, I'm done! Thanks for pointing this out though!
    – Dav Clark
    May 10, 2011 at 5:15
  • Has this stabilised at all?
    – naught101
    Jul 7, 2014 at 5:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.