3 Functions

3.1 Naming

Use verbs for function names, where possible.

3.3 return()

Only use return() for early returns. Otherwise, rely on R to return the result of the last evaluated expression.

If your function is called primarily for its side-effects (like printing, plotting, or saving to disk), it should return the first argument invisibly. This makes it possible to use the function as part of a pipe. print methods should usually do this, like this example from httr:


In code, use comments to explain the “why” not the “what” or “how”. Each line of a comment should begin with the comment symbol and a single space: #.

3.5 Design

There are two main design principles to bear in mind:

  • A function should do one thing well.

    A function should be called either because it has side-effects or because it returns a value; not both. Strive to keep blocks within a function on one screen. 20-30 lines per function are common. For functions that are significantly longer, consider splitting it into smaller functions.

  • A function should be easily understandable in isolation.

    Avoid global options. If your function has a transient side-effect (i.e. you need to create a temporary file or set an option), clean up after yourself with on.exit().