R Functions
In programming, a function is a group of instructions that you want to use repeatedly, because of their complexity, are better self-contained in sub-program and called when needed. Hence, we can say that a function is a set of code written to perform a specific task; it cannot or can accept arguments or parameters and it cannot or can return one or more values.
In R programming language, a function is an object, so the R interpreter is able to pass control to the function, along with the arguments that may be important for the function to accomplish the actions.
R provides a large number of in-built functions and the user can create their own functions.
Syntax for Function Definition
function_name <- function(arguments) { # Function body return (object) }
Here,
function_name is the name of the function. In R environment it is stored as an object with this name.
function is a reserved keyword used to declare a function.
arguments is the number of values you can pass in a function. This is optional.
Function body defines within the curly braces which contain a number of statements. These braces are optional if the body contains only a single statement.
Return value is the last expression in the body of the function to be evaluated.
Built-in Functions
We can categorize the built in functions into following groups:
1. Numeric Function
Function |
Description |
Example |
abs(x) |
Returns the absolute value of x |
a <- abs(x) |
sqrt(x) |
Returns the Square root of x |
a <- sqrt(33.45) |
log(x) |
Returns the natural log of x |
a <- log(200) |
exp(x) |
Returns the exponential of x |
a <- exp(10) |
sin(x), cos(x), tan(x) |
Returns sine, cosine, or tangent of a value |
a <- sin(x) |
round(x, digits =n) |
Rounding of number |
Round(3.475, digits =2) is 3.48 |
floor(x) |
Rounding of number |
floor(1.475) is 1 |
2. Statistical Functions
Function |
Description |
Example |
mean(x) |
Returns the mean or average of a set of numbers |
y <- c(20, 30, 22) result.mean <- mean(y) |
median(x) |
Median of x |
result.median <- median(y) |
mode |
Returns the mode of a range |
result.mode <- mode(y) |
sd(y) |
Shows the standard deviation of range |
print(sd(y)) |
range(y) |
Returns the range of values |
print(range(y)) |
pnorm(y) |
Shows the normal probability of a number |
pnorm(2.334) |
sum(x) |
Returns the sum of a range |
sum(y) |
min(x) |
Returns the minimum of a range |
min(y) |
max(x) |
Returns the maximum of a range |
max(y) |
3. Character Functions
Function |
Description |
Example |
subtstr(x, start =n1, stop =n2) |
Extract or replace substrings in a character vector |
substr(“abcdef”, 2, 4) |
grep(pattern, x, ignore.case = FALSE, fixed = FALSE) |
Search for pattern in x. if fixed = FALSE then pattern is a regular expression. Else pattern is a text string. returns matching indices |
grep(“A”, c(“b”, “A”, “c”), fixed = TRUE) returns 2 |
toupper(x) |
Upper case |
x <- “MiXeD Case” toupper(x) |
tolower(x) |
Lower case |
tolower(x) |
User Defined Function
We can create our own function in R. Let’s create a function called pow() :
Example 1:
pow <- function(x,y){ result <- x^y print(result)
Calling Function
We can call the above function pow() as follows:
> pow(9,2)
Output will be:
[1] 81
Named Arguments
In the above function calls, the position of formal argument and actual argument must be in order.
Means from the above example of function call pow(9, 2), the formal arguments x and y are assigned 9 and 2 respectively.
We can also call the function by name. when calling the function in this way, the order of the actual argument does not matter.
For example:
> pow(9, 2) [1] 81 > pow(x = 9, y= 2) [1] 81 > pow(y = 2, x = 9) [1] 81
We can also use named and unnamed arguments in a single call.
> pow(x = 9, 2) [1] 81 > pow(2, x = 9) [1] 81
Default values for Arguments
In R, we can assign default values to arguments of a function.
This is done in the function declaration by providing an appropriate value to the formal argument.
Let's add the above example again by adding a default value to y:
pow <- function(x, y = 2){ result <- x^y print (result) }
The use of default value to an argument of a function makes it optional when calling the function.
> pow(9) [1] 81 > pow(3, 3) [1] 27
Let's see another example of user-defined function.
Example 2:
# creating a function addition <- function (a, b){ add <- a+b # returning a value return(add) } #calling the function addition(20, 30)
Output:
[1] 50
Example 3:
Let's create a user-defined function to accept two matrix arguments and do matrix operation with the same:
MatSum<-function(M1,M2){ print("The Matrix1") print(M1) print("The Matrix2") print(M2) summat<-M1+M2 print("Sum of Matrices") print(summat) } Mat1 <- matrix(1:9, nrow = 3,ncol=3,byrow = TRUE) Mat2 <- matrix(0:8, nrow = 3,ncol=3,byrow = TRUE) MatSum(Mat1,Mat2)
Output:
[1] "The Matrix1" [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 [1] "The Matrix2" [,1] [,2] [,3] [1,] 0 1 2 [2,] 3 4 5 [3,] 6 7 8 [1] "Sum of Matrices" [,1] [,2] [,3] [1,] 1 3 5 [2,] 7 9 11 [3,] 13 15 17
Example 4:
Create a function to accept a name from the user. uname <- function() { str <- readline(prompt="Enter the Name: ") return(as.character(str)) } print(uname())
Output:
Enter the Name: Nikita [1] "Nikita"Reference: https://www.guru99.com/r-functions-programming.html https://swcarpentry.github.io/r-novice-inflammation/02-func-R/