Creating A Function In R
Make Your Basic (and later complex) Calculations Easy
--
The R Program allows one to create and use their own function in order to make data processing easy. Here, I will be taking the Quadratic Formula, creating it in R and will run the function with some example to show how R can make calculations easier regardless of whether one aims to use R for statistics for simply for the fun of it.
The Quadratic Formula allows one to find the solutions for a quadratic equation, typically: ax² + bx + c = 0, where one can solve for the value for ‘x’ given the value of ‘a’, ‘b’ and ‘c’. The Formula for solving for the value of ‘x’ can be seen on the left.
In R, to create a function, we first have to define the new function we are creating. Lets call our new function value_x. We then have to create the function by defining the inputs. Here the inputs are ‘a’, ‘b’, and ‘c’. Then we have to define the operation that needs to occur. Here that is the one that is seen above. Then we have to define the output that we need. This, in the context of the quadratic equation, would look like this.
value_x <- function(a, b, c){
x = (((-b) + c(-1, 1) * sqrt((b²) — 4 * a * c))) / (2*a)
x
}
This now defines the function that we can use. So instead of conducting each iteration by hand we can simply ask R to calculate it for us. We can do this by simply typing: value_x(a, b, c) where we input the values of a, b, and c and R will automatically, according to the function, calculate the two values of x for us. As can be seen on the left. Similarly, one can program many other function from converting Celsius to Fahrenheit, to data specific formulas.
Gain Access to Expert View — Subscribe to DDI Intel