Here we will discuss what functions are in R, and how to create simple functions for calculations in R.

For creating algorithms, see the pages on for loop, if-else and while loop statements.

Learning about operations in R will also be useful.

1 What Are Functions in R

A function in R is an object that performs a specific task or set of tasks. A function takes one or more arguments. When it is called and its argument(s) is(are) specified, the function returns one or more values as designed.

In R, to set up a function, you need to define:

  • the argument(s) the function will take as input;

  • the chunk of code that will operate on the input towards completing the task(s);

  • and finally, the output the function will return.

There are several functions available in the base version of R available through packages such as the "base", "stats" and "utils" packages. These functions perform varying tasks such as computation, data manipulation, graphics and so on. In addition to these, you can create functions to perform tasks of interest.

2 A Function to Calculate the Z-value in R

To calculate the z-value of a number (often used in statistical tests), based on the formula:

\[z = {(x-m) \over sd}\] The arguments from the equation are the value of \(x\), the mean \(m\), and the standard deviation \(sd\).

To create the function, use:

zvalue = function(x, mean, sd){
  z = (x-mean)/sd
  return(z)
}

You can then evaluate the z-value for \(x=8\) with mean as \(2\), and standard deviation as \(4\):

zvalue(8, 2, 4) # Note that the order 8, 2, 4 is important.
[1] 1.5

You can set default values for the arguments:

zvalue = function(x = 8, mean = 2, sd = 4){
  z = (x-mean)/sd
  return(z)
}

You can then evaluate the z-value for the default values:

zvalue()
[1] 1.5

Or you can then evaluate the z-value for \(x=10\), and \(\text{(mean, sd)} = (4, 1)\):

# mean = 2, sd = 4 as in the default
zvalue(x = 10)
[1] 2
# x = 8, as in the default
zvalue(mean = 4, sd = 1)
[1] 4

3 A Function to Calculate the Area of a Circle in R

To calculate the area of a circle, using the formula:

\[Area = \pi r^2\] The variable in the equation is the radius, \(r\), and the constant \(\pi\) is available in R as pi.

To create the function, use:

AreaCircle = function(r){
  area = pi*(r^2)
  return(area)
}

If you prefer to use another value for \(pi\), say \(22/7\), and have some statement in the output, then use:

AreaCircle22 = function(r){
  pi=22/7
  area = pi*(r^2)
  return(paste("The area of a circle with radius", r, "is:", area))
}

You can then evaluate the area of a circle with \(r=7\):

AreaCircle(7)
[1] 153.938
AreaCircle22(7)
[1] "The area of a circle with radius 7 is: 154"

Copyright © 2020 - 2024. All Rights Reserved by Stats Codes