Although there are many functions in the base package of R, sometimes there may not be a function that does exactly what you want. In this case, R allows users to create their own functions and call upon them. This can be very helpful when you have to perform the same series of steps over and over again in a script. The basic structure of a user-created function is given below:
nameOfFunction <- function(argument1, arguement2, ...){
# code to execute
return(output)
}
function()
is called. This is not a user defined function, but is one that is defined in the R base package. This means that any R user can use this function without downloading third party packages.return()
is called to indicate the output of the function.Below is an example of a user-created function:
# A function to calculate the sum from 1 to a specified number sumTo <- function(number){ x <- 0
for (i in 1:number){
x <- x + i
} return(x)
} # example call of the function after it has been defined
sumTo(5)
x
equal to zero. This is called 'space allocation.'return()
is used so that the function will output the result from the for loop, and the final curly bracket tells R that the function call has ended.sumTo()
function using the input value of 5, from which the value 15 will be returned since 1+2+3+4+5=15.Similar to saving R scripts as external files, you can also save R functions. By saving an R function as an external file, you can then call your function in other scripts that you write. However, before you can call your function you first have to load your function into your Global Environment. This is called sourcing a function, which is done by using the source()
function in R. For instance, let's assume that the above example function sumTo()
has been saved in a folder on your Desktop call R_is_Awesome and you would like to use this function without having to copy/paste the actual lines of code into your current script. In that case, you could do the following:
# first source the function to load it into your Global Environment
source('/Users/username/Desktop/R_is_Awesome/sumTo.R')
# then you can call the function
sumTo(5)
Note: The only argument of source()
is a character string formed by combining the file path to the function and the name of the function including the .R
file type.
501 E. High Street
Oxford, OH 45056
1601 University Blvd.
Hamilton, OH 45011
4200 N. University Blvd.
Middletown, OH 45042
7847 VOA Park Dr.
(Corner of VOA Park Dr. and Cox Rd.)
West Chester, OH 45069
Chateau de Differdange
1, Impasse du Chateau, L-4524 Differdange
Grand Duchy of Luxembourg
217-222 MacMillan Hall
501 E. Spring St.
Oxford, OH 45056, USA