next up previous
Up: Introduction to S Previous: Data Structures

Writing Functions in S

Often there is a sequence of commands that you wish to use repeatedly. Rather than typing it in each time, it is often easier to create a function to execute the set of commands for you. See Becker, Chambers, and Wilks for details; here is a simple example which plots the theoretical histogram of a binomial distribution (n independent trials each with probability p of `success').

hbinom<-function(n,p)
{
# plots a relative frequency histogram of the binomial distribution
k<-0:n
p<-dbinom(k,n,p)
w<-seq(-1/2,n+1/2,1)
barplot(p,width=w,histo=T,col=0)
}
If you type the name of the function without the parentheses, S will respond by printing out the function. Another way to create a function is to use your favorite UNIX editor to create a file containing the function specification, and then use the `source' function to read it into S.

Albyn Jones
Tue Jun 25 11:03:47 PDT 1996