As a programming language for computing and modeling, R is full of functions. Same as in many other programming languages, a function in R takes an input (also called arguments) and then produces (returns) an output in the following format
myfunction<-function(argument1, argument2, ..., argumentn )
{
R statements; ##Body of a function
return(output);
}
We will give a few examples in the following.
1. Number of positive items in a list.
2. Finding non-duplicate items in a list.
5. Second max value of a list. We will write a simple function that has a list of numbers as input, then output the value of the second largest (return -infinity if there is only one item in the list).
secMax<-function(x)
{
infty<-10^20; #define this as a very large number;
n<-length(x);
if(n <2) return(-infty);
mysec<--infty;
mymax<-x[1];
for(i in 2:n)
{
if(x[i] > mymax)
{
mysec<-mymax;
mymax<-x[i];
}
else
{
if(x[i] > mysec)
{
mysec<-x[i];
}
}
}
return(mysec);
}
To be able to call the above function, say secMax(), one first load it into R running time environment, i.e., copy the above code and paste in R command panel. To invoke the function, one prepares a list of numbers, say x, and then call the function by secMax(x). An example session goes as follows.
> zz<-c(1)
> secMax(zz)
[1] -1e+20
> zz<-c(1,9,10,10000,20,400)
> secMax(zz)
[1] 400
Another way to call the function is to save the R code to a file, say "myCode.R", in the working directory.
Then load the code to R running time environment, and call the function
>source("myCode.R");
>secMax(c(1,9,10,10000,20,400))