# Creating functions in R

Functions are used to simplify a series of calculations.

For instance, let us suppose that there exists an array of numbers which we wish to add to another variable. Instead of carrying out separate calculations for each number in the array, it would be much easier to simply create a function that does this for us automatically.

A function in R generally works by:

(a) Defining the variables to include in the function and the calculation. e.g. to add two numbers together, our function is:

function(number1,number2) {(number1+number2)}

(b) Using sapply to define the list of numbers and typically an associated sequence:

Here’s a few examples below that you can try out for yourself!

1. Add an array of numbers to a sequence

> result1df<-data.frame(result1)
> result1df

X1 X2 X322 42 62 24 44 64 26 46 66 28 48 68 30 50 70 32 52 72 34 54 74 36 56 76 38 58 78 140 60 80

2. Subtract an array of numbers from a sequence

> number1minusnumber2<-function(number1,number2) {(number1-number2)}

> result2<-sapply(c(20,40,60),number1minusnumber2,seq(2,20,by=2))
> result2df<-data.frame(result2)
> result2df

X1 X2 X318 38 58 16 36 56 14 34 54 12 32 52 10 30 50 8 28 48 6 26 46 4 24 44 2 22 42 0 20 40

3. Multiply an array of numbers by a sequence

> multiplynumber1bynumber2 <-function(number1,number2) {(number1*number2)}

> result3<-sapply(c(20,40,60), multiplynumber1bynumber2, seq(2,20, by=2))
> result3df=data.frame(result3)
> result3df

X1 X2 X340 80 120 80 160 240 120 240 360 160 320 480 200 400 600 240 480 720 280 560 840 320 640 960 360 720 1080 400 800 1200

4. Divide an array of numbers by a sequence

> dividenumber1bynumber2<-function(number1,number2) {(number1/number2)}

> result4<-sapply(c(20,40,60), dividenumber1bynumber2, seq(2, 20, by=2))
> result4df<-data.frame(result4)
> result4df

X1 X2 X310.000000 20.000000 30.000000 5.000000 10.000000 15.000000 3.333333 6.666667 10.000000 2.500000 5.000000 7.500000 2.000000 4.000000 6.000000 1.666667 3.333333 5.000000 1.428571 2.857143 4.285714 1.250000 2.500000 3.750000 1.111111 2.222222 3.333333 1.000000 2.000000 3.000000

5. Raise number to a power

> raisenumber1bypower<-function(number1,power) {(number1^power)}
> result5<-sapply(c(20,40,60),raisenumber1bypower,seq(0.5,2.5,by=0.5))
> result5df<-data.frame(result5)
> result5df

X1 X2 X34.472136 6.324555 7.745967 20.000000 40.000000 60.000000 89.442719 252.982213 464.758002 400.000000 1600.000000 3600.000000 1788.854382 10119.288513 27885.480093