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.
# GOODPredictCTR <- function(query, property, num.days,show.plot = TRUE)# BADPredictCTR <- 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
- A one-sentence description of the function;
- A list of the function’s arguments, denoted by
Args:
, with a description of each (including the data type), and, - 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:
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 handlingif (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.
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)
.