Functions in R

How to define a function in R

Functions are defined using the function() directive and are stored as R objects just like anything else. In particular, they are R objects of class “function”. Here’s a simple function that takes no arguments simply prints ‘Hi statistics’.

 

#define the function
f <- function() {

print("Hi statistics!!!")
}
#Call the function
f()

Output:

[1] "Hi statistics!!!"

 

Now let’s define a function called standardize, and the function has a single argument x which is used in the body of function.

 

#Define the function that will calculated standardized score.
standardize = function(x) {
m = mean(x)
sd = sd(x)
result = (x - m) / sd
result
}

#Take input for what we want to calculate standardized score.
input<- c(40:50)
standardize(input) #Call the function

Output:

> standardize(input) #Call the function
 [1] -1.5075567 -1.2060454 -0.9045340 -0.6030227 -0.3015113 0.0000000 0.3015113 0.6030227 0.9045340 1.2060454 1.5075567

Here is an example of a simple function in R that takes two arguments and returns their sum:

my_function <- function(a, b) {
result <- a + b
return(result)
}

In the above example, my_function is the function name, and a and b are the parameters passed to the function. The function body is enclosed in curly braces, and it consists of two statements: one that adds a and b together and assigns the result to result, and another that returns the value of result.

To call this function, you can simply pass in two arguments:

sum_result <- my_function(2, 3)
print(sum_result) # Output: 5

In this example, 2 and 3 are the arguments passed to my_function. The function adds them together and returns the result 5, which is stored in the variable sum_result. Finally, the print() function is used to display the value of sum_result on the screen.

Control Structures

Data Basics: Summary Statistics