Writing a Function

Below is a video on how to write a function for R. If you would prefer to read, just skip it.

Many times, there will be instances where we will need to make our own functions. Even though there are many functions available through R and its packages, we may still need to create our own that work in specific situations.  If you do not know what a function is, click here first to find out what they are.

We will walk through creating a function in R.   The general format for a function in R is the following:

#general set-up for a function

FUNCT<- function(parameter1, parameter2, parameter3, ...){

#put what you want the function to compute here

}#these special brackets are important 
#as the denoted the beginning and end of the function


We will now try to create a specific function in R. Let us create one for the mean. We will do this because it is a good first learning experience and will be able to be checked with mean(). Here is one possible way to create this function:

#mean custom function

MEAN<-function(x){

s<-sum(x)
l<-length(x)
final<-s/l

return(final)

}

Question I

Write an alternative function than the way we provided to calculate the mean for the following set of data. Compare it to the function mean().

Observation

Data

1 1.89
2 11.89
3 10.75
4 5.68
5 11.86

Answer I

The following is the code to solve this. There are other ways to solve this. Notice that the mean() and our custom function both provide the same answer.  Below the code is the output in R.

MEAN<-function(x){


l<-length(x)
s<-x/l

final<- sum(s)

return(final)

}


#using the function on the data
data<-c(1.89, 11.89, 10.75, 5.68, 11.86)

MEAN(data)
mean(data)

 

Figure 1
Figure 1