User defined functions

Sometimes we want to write a function to do a very specific job, because we cannot find an exact equivalent, and/or the procedure has to be executed a number of times in a piece of code. Most programming languages allow us to define functions. We define the source code for the function, that is, the code that R looks for whenever the function is called.

The example function below outputs a person’s name, along with the number and type of pets they have.

The function code is enclosed within the curly braces {}.


    return(result)             #the function returns the last object it sees.  
                               #Adding a return() specifies what to return to
                                the main program
                               #But is not strictly necessary here. Try the
                                code without it.  


details<-name_pets(name, number_of_cats,number_of_dogs)  #this is the function
                                    call. The arguments passed to the function 
                                    #do not have to have the same names as in
                                    the source code.

details           #The function output is contained within the object 'details' 
                  #until a command is given to display it.

'Andrew' '4' '1'