1.16 Creating a function

You can easily create your own functions in R. Let’s create a function that computes the odds ratio for a two-by-two table. Notice how I added some comments to make it clear what the function is doing.

OR <- function(a, b, c, d) {
  # 2x2 table, E=exposure, D=disease
  #     | D+ |  D-
  #  --------------
  #  E+ | a  |  b
  #  --------------
  #  E- | c  |  d
  #  --------------
  # Compute the odds ratio of the table
  # using the cross-product
  return((a*d)/(b*c))
}

Typing the name of the function without any parentheses or arguments will display the function’s code.

OR
## function(a, b, c, d) {
##   # 2x2 table, E=exposure, D=disease
##   #     | D+ |  D-
##   #  --------------
##   #  E+ | a  |  b
##   #  --------------
##   #  E- | c  |  d
##   #  --------------
##   # Compute the odds ratio of the table
##   # using the cross-product
##   return((a*d)/(b*c))
## }

To call the function, type the name along with some arguments.

OR(25, 10, 18, 12)
## [1] 1.667

Functions can be far more complex than this example and are very useful. For further study, see RStudio Cloud’s primer on writing functions.