...

/

Function definitions, function calls and source files

Function definitions, function calls and source files

This lesson is all about correctly writing a function - its definition, call and source file.

Function Definitions and Calls

Function definitions should first list arguments without default values, followed by those with default values.

In both function definitions and function calls, multiple arguments per line are allowed; line breaks are only allowed between assignments.

Press + to interact
# GOOD
PredictCTR <- function(query, property, num.days,
show.plot = TRUE)
# BAD
PredictCTR <- function(query, property, num.days, show.plot =
TRUE)

Function Documentation

Functions should contain a comments section immediately below the function definition line. These comments should consist of

  1. A one-sentence description of the function;
  2. A list of the function’s arguments, denoted by Args:, with a description of each (including the data type), and,
  3. A description of the return value, denoted by Returns:.

The comments should be descriptive enough that a caller can use the function without reading any of the function’s code.

Have a look at the sample function below:

Press + to interact
CalculateSampleCovariance <- function(x, y, verbose = TRUE) {
# Computes the sample covariance between two vectors.
#
# Args:
# x: One of two vectors whose sample covariance is to be calculated.
# y: The other vector. x and y must have the same length, greater than one,
# with no missing values.
# verbose: If TRUE, prints sample covariance; if not, not. Default is TRUE.
#
# Returns:
# The sample covariance between x and y.
n <- length(x)
# Error handling
if (n <= 1 || n != length(y)) {
stop("Arguments x and y have different lengths: ",
length(x), " and ", length(y), ".")
}
if (TRUE %in% is.na(x) || TRUE %in% is.na(y)) {
stop(" Arguments x and y must not have missing values.")
}
covariance <- var(x, y)
if (verbose)
cat("Covariance = ", round(covariance, 4), ".\n", sep = "")
return(covariance)
}

As an alternative, you can also use the comment(FunctionName) function in R to comment your function, so that when anyone else uses that function they can actually see the comment directly.

Press + to interact
comment(CalculateSampleCovariance) <- c("Computes the sample covariance between two vectors.",
"Args:
x: One of two vectors whose sample covariance is to be calculated.
y: The other vector. x and y must have the same length, greater than one, with no missing values.
verbose: If TRUE, prints sample covariance; if not, not. Default is TRUE." )

This will allow you to see the comments directly simply by calling str(FunctionName).