5.3 Tips for functions

  • Look on CRAN, Bioconductor or other repositories first to see if others have created the function you need. If so, test their function first.

  • Like variables, give functions a meaningful and self-explanatory name.

  • Keep functions simple and structured, that is, only do one thing.

  • Use some form of indentation to keep your code readable so that you can follow what is happening. Have a look at the R coding conventions and links contained within at http://journal.rproject.org/archive/2012-2/RJournal_2012-2_Baaaath.pdf.

  • An explicit return() is not required in a function. By default a function will return the last executed command. However, it is worthwhile to include a return statement if you have a complicated function that has multiple endpoints and logical decisions. This also makes debugging easier.
    • You can also create and return complex data structures e.g. return(list(...))

If you think that writing a function is great, the next step will be to write whole packages that automate, streamline and focus your research. This is not difficult but unfortunately does not fit in the scope of this workshop.