Togaware DATA MINING
Desktop Survival Guide
by Graham Williams
Google

Functions



myfun <- function(arg1, arg2=TRUE, ...)
{
  [...] 
}

The results of a function are returned with the return function (or else is the result of the last evaluated statement in the function). The returned result will be printed if the result is not assigned to a variable. To avoid the result being printed, use the invisible function to return the result.

Anonymous functions can be used:

(function(x, y) x^2 + y^2)(0:5, 1)	#  1  2  5 10 17 2

Functions are first class objects. You can write a function to return a function:

f <- function(y=10) 
{
  g <- function(x) seq(x, x+y)
  return(g)
}
> h <- f(5)
> h(5)
[1]  5  6  7  8  9 10
> h <- f()
> h(5)
 [1]  5  6  7  8  9 10 11 12 13 14 15
> get("y",env=environment(h))
[1] 10

And you can write a function to apply some given function:

chooseFun<-function(dat=1:10,fun=mean,...)fun(dat,...)
chooseFun()
x<-rnorm(100)
chooseFun(x,median)
chooseFun(x,hist)
chooseFun(x,hist,col='gray')



Copyright © 2004-2006 [email protected]
Support further development through the purchase of the PDF version of the book.
Brought to you by Togaware.