Previous: Programming Statements Up: Programming Statements Next: If-Statements

Functions

Functions are either built-in or user-defined sets of encapsulated commands which may take any number of arguments. Preface a function with the function statement and use the <- operator to assign functions to objects in your workspace.

You may use functions to run the same procedure on different objects in your workspace. For example,

check <- function(p, q) { 
 result <- (p - q)/q
 result
 }
is a simple function with arguments p and q which calculates the difference between the 4#4 th elements of the vector p and the 4#4 th element of the vector q as a proportion of the 4#4 th element of q, and returns the resulting vector. For example, check(p = 10, q = 2) returns 4. You may omit the descriptors as long as you keep the arguments in the correct order: check(10, 2) also returns 4. You may also use other objects as inputs to the function. If again = 10 and really = 2, then check(p = again, q = really) and check(again, really) also returns 4.

Because functions run commands as a set, you should make sure that each command in your function works by testing each line of the function at the R prompt.



Gary King 2011-11-29