Functions
Functions are the block of code that given the user the ability to reuse the same code which saves the excessive use of memory and provides better readability to the code. So basically, a function is a collection of statements that perform some specific task and return the result to the caller. Functions are created in R by using the command function() keyword
Example:
R
# A simple R program to # demonstrate functions ask_user = function (x){ print ( "w3wiki" ) } my_func = function (x){ a <- 1:5 b <- 0 for (i in a){ b = b +1 } return (b) } ask_user () res = my_func () print (res) |
Output:
[1] "w3wiki" [1] 5
Function with Arguments:
Arguments to a function can be specified at the time of function definition, after the function name, inside the parenthesis.
Example:
R
# A simple R function to check # whether x is even or odd evenOdd = function (x){ if (x %% 2 == 0) # return even if the number # is even return ( "even" ) else # return odd if the number # is odd return ( "odd" ) } # Function definition # To check a is divisible by b or not divisible <- function (a, b){ if (a %% b == 0) { cat (a, "is divisible by" , b, "\n" ) } else { cat (a, "is not divisible by" , b, "\n" ) } } # function with single argument print ( evenOdd (4)) print ( evenOdd (3)) # function with multiple arguments divisible (7, 3) divisible (36, 6) divisible (9, 2) |
Output:
[1] "even" [1] "odd" 7 is not divisible by 3 36 is divisible by 6 9 is not divisible by 2
- Default Arguments: Default value in a function is a value that is not required to specify each time the function is called.
Example:
R
# Function definition to check # a is divisible by b or not. # If b is not provided in function call, # Then divisibility of a is checked # with 3 as default isdivisible <- function (a, b = 9){ if (a %% b == 0) { cat (a, "is divisible by" , b, "\n" ) } else { cat (a, "is not divisible by" , b, "\n" ) } } # Function call isdivisible (20, 2) isdivisible (12) |
Output:
20 is divisible by 2 12 is not divisible by 9
- Variable length arguments: Dots argument (…) is also known as ellipsis which allows the function to take an undefined number of arguments.
Example:
R
# Function definition of dots operator fun <- function (n, ...){ l <- c (n, ...) paste (l, collapse = " " ) } # Function call fun (5, 1L, 6i, TRUE , "GFG" , 1:2) |
Output:
5 1 0+6i TRUE GFG 1 2
Refer to the below articles to get detailed information about functions in R
Learn R Programming
R is a Programming Language that is mostly used for machine learning, data analysis, and statistical computing. It is an interpreted language and is platform independent that means it can be used on platforms like Windows, Linux, and macOS.
In this R Language tutorial, we will Learn R Programming Language from scratch to advance and this tutorial is suitable for both beginners and experienced developers).
Contact Us