Instruction Aside from your handwritten or typed report with
Solution
One of the great strengths of R is the user\'s ability to add functions. In fact, many of the functions in Rare actually functions of functions. The structure of a function is given below.
myfunction <- function(arg1, arg2, ... ){
 statements
 return(object)
 }
Objects in the function are local to the function. The object returned can be any data type. Here is an example.
# function example - get measures of central tendency
 # and spread for a numeric vector x. The user has a
 # choice of measures and whether the results are printed.
 
 mysummary <- function(x,npar=TRUE,print=TRUE) {
   if (!npar) {
     center <- mean(x); spread <- sd(x)
   } else {
     center <- median(x); spread <- mad(x)
   }
   if (print & !npar) {
     cat(\"Mean=\", center, \"\ \", \"SD=\", spread, \"\ \")
   } else if (print & npar) {
     cat(\"Median=\", center, \"\ \", \"MAD=\", spread, \"\ \")
   }
   result <- list(center=center,spread=spread)
   return(result)
 }
 
 # invoking the function
 set.seed(1234)
 x <- rpois(500, 4)
 y <- mysummary(x)
 Median= 4
 MAD= 1.4826
 # y$center is the median (4)
 # y$spread is the median absolute deviation (1.4826)
 
 y <- mysummary(x, npar=FALSE, print=FALSE)
 # no output
 # y$center is the mean (4.052)
 # y$spread is the standard deviation (2.01927)
It can be instructive to look at the code of a function. In R, you can view a function\'s code by typing the function name without the ( ).
These are some good programing techniques in general.
Writing Functions
Functions in R can do 3 things
The R function Statement
The basic R function statement looks like this
 FUNname <- function( arglist ) { code }
Function Return Values
Functions are designed to return values. It is call returning because the value is taken from the function and is returned to the calling code.


