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.
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.
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:
You can then evaluate the z-value for \(x=8\) with mean as \(2\), and standard deviation as \(4\):
[1] 1.5
You can set default values for the arguments:
You can then evaluate the z-value for the default values:
[1] 1.5
Or you can then evaluate the z-value for \(x=10\), and \(\text{(mean, sd)} = (4, 1)\):
[1] 2
[1] 4
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:
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\):
[1] 153.938
[1] "The area of a circle with radius 7 is: 154"
The feedback form is a Google form but it does not collect any personal information.
Please click on the link below to go to the Google form.
Thank You!
Go to Feedback Form
Copyright © 2020 - 2024. All Rights Reserved by Stats Codes