Writing your own functions



next up previous contents
Next: Defining new binary Up: Notes on S-PLUS: A Previous: Control statements

Writing your own functions

 

As we have seen informally along the way, the S-PLUS language allows the user to create objects of mode function. These are true S-PLUS functions that are stored in a special internal form and may be used in further expressions and so on. In the process the language gains enormously in power, convenience and elegance, and learning to write useful functions is one of the main ways to make your use of S-PLUS comfortable and productive.

It should be emphasized that most of the functions supplied as part of the S-PLUS system, such as mean(), var(), postscript() and so on, are themselves written in S-PLUS and thus do not differ materially from user written functions.

A function is defined by an assignment of the form

name <- function(arg, arg, ... ) expression

The expression is an S-PLUS expression, (usually a grouped expression), that uses the arguments, arg, to calculate a value. The value of the expression is the value returned for the function.

A call to the function then usually takes the form name(expr, expr, ...) and may occur anywhere a function call is legitimate.

For example, consider a function to emulate directly the MATLAB backslash command, which returns the coefficients of the orthogonal projection of the vector onto the column space of the matrix, . Thus given a vector and a matrix then

where is a generalized inverse of .

> bslash <- function(X, y) 
  {
        X <- qr(X)
        qr.coef(X, y)
  }

After this object is created it is permanent, like all objects, and may be used in statements such as

regcoeff <- bslash(Design, yvar)

and so on.

The classical S-PLUS function lsfit() does this job quite well, and more. It in turn uses the functions qr() and qr.coef() in the slightly counterintuitive way above to do this part of the calculation. Hence there is probably some value in having just this part isolated in a simple to use function if it is going to be in frequent use. If so, we may wish to make it a matrix binary operator for even more convenient use.





next up previous contents
Next: Defining new binary Up: Notes on S-PLUS: A Previous: Control statements



Erik Moledor
Tue Jan 31 21:02:18 EST 1995