User Defined Functions


Function are defined by collections of statements of the form


variable <- function(arglist) 
{
R expressions
   *
   *
return(value);
}


This statement creates a function of name variable, that may be invoked by the statement variable(arglist). If return is omitted, then the return value is the result of the last executable statement.

When executing functions, if the code gets into an endless loop, hit the "Stop" symbol in the GUI menu.

Function definitions can be made in .R files or on the command line.

Functions defined in the .R files must be "sourced" before they are available.Additionally, if one
changes a function definition in a .R file, the file must be re-"sourced" to load in the new version.

When functions are assigned to a variable, that variable may be passed as a parameter to other routines.

To toggle a function for debugging, use the debug(fun) command. If a function is toggled for debugging, the invocation of the function causes normal execution to be suspended and the body of function is executed one statement at a time. See debug for details.

Use args and body for accessing the arguments and body of a function.

Use invisible for return(.)ing invisibly.

See Also : Executing/Loading R Source Files

Original Documentation : functions, debug, args, body, invisible

Samples

# Defining a sin(x)^2 function

sin2 <- function(x)
{
return (sin(x)^2);
}

# Using the previously defined sin2 function in the command line

> sin2(1.0);
[1] 0.7080734

# Creating a function that plots functions over an
# interval[a,b]

plotFun <- function(f,a,b)
{
n <- 100;                 # number of panels
x <- seq(a,b,(b-a)/n);    # generate ordinates
y <- f(x);                # generate abscissas by invoking f(...)
plot(x,y,type='l');       # create line plot 
}

# Creating a function that returns the norm of a vector
# as a double

norm <- function(x)
{
y <- as.double(sqrt(x%*%x));
return(y);
}


UCLA Mathematics Department ©2000