Functions in R
Functions in R
Introduction
A function is a reusable block of code that performs a specific task. Functions help divide a large program into smaller, manageable modules, thereby improving readability, maintainability, and code reusability.
Functions in R are broadly classified into:
- Built-in Functions
- User-defined Functions
- Recursive Functions
1. Built-in Functions
Definition
Built-in functions are predefined functions provided by R. These functions are readily available and can be used directly without any additional definition. They perform commonly required tasks such as mathematical calculations, statistical analysis, string manipulation, and input/output operations.
Advantages
- Reduce programming effort.
- Improve readability.
- Save development time.
- Provide optimized implementations.
Syntax
function_name(arguments)
Example:
sqrt(25)
sum(c(10,20,30))
print("Hello")
Categories of Built-in Functions
Mathematical Functions
| Function | Purpose |
|---|---|
abs() | Absolute value |
sqrt() | Square root |
exp() | Exponential function |
log() | Natural logarithm |
round() | Round a number |
Example
print(abs(-20))
print(sqrt(49))
print(round(3.4567,2))
Output
[1] 20
[1] 7
[1] 3.46
Statistical Functions
| Function | Purpose |
|---|---|
sum() | Sum of elements |
mean() | Average |
median() | Median value |
max() | Maximum element |
min() | Minimum element |
Example
x <- c(10,20,30,40)
print(sum(x))
print(mean(x))
print(max(x))
Output
[1] 100
[1] 25
[1] 40
String Functions
| Function | Purpose |
|---|---|
nchar() | String length |
toupper() | Convert to uppercase |
tolower() | Convert to lowercase |
substr() | Extract substring |
Example
name <- "Computer"
print(nchar(name))
print(toupper(name))
Output
[1] 8
[1] "COMPUTER"
Input-Output Functions
| Function | Purpose |
|---|---|
print() | Display output |
cat() | Concatenate and display |
readline() | Read input |
scan() | Read multiple values |
Data Type Functions
| Function | Purpose |
|---|---|
class() | Determines class |
typeof() | Determines storage type |
length() | Number of elements |
Example
x <- c(1,2,3)
print(class(x))
print(length(x))
2. User-defined Functions
Definition
A user-defined function is a function created by the programmer to perform a specific task. User-defined functions improve modularity and eliminate repetition of code.
Syntax
function_name <- function(parameters)
{
statements
return(value)
}
where
- function_name is the name of the function.
- parameters are input arguments.
- return() returns the result to the calling program.
Example 1: Function Without Arguments
greet <- function()
{
print("Welcome to R Programming")
}
greet()
Output
[1] "Welcome to R Programming"
Example 2: Function with Arguments
square <- function(x)
{
return(x*x)
}
print(square(5))
Output
[1] 25
Example 3: Function with Multiple Arguments
add <- function(a,b)
{
return(a+b)
}
print(add(10,20))
Output
[1] 30
Example 4: Function Without Explicit Return
largest <- function(a,b)
{
if(a>b)
a
else
b
}
print(largest(15,20))
Output
[1] 20
R automatically returns the value of the last expression.
Example 5: Function to Find Factorial Using a Loop
factorial <- function(n)
{
fact <- 1
for(i in 1:n)
{
fact <- fact*i
}
return(fact)
}
print(factorial(5))
Output
[1] 120
Advantages of User-defined Functions
- Avoid code duplication.
- Increase readability.
- Simplify debugging.
- Promote modular programming.
- Improve code reusability.
3. Recursive Functions
Definition
A recursive function is a function that calls itself repeatedly to solve a problem. Each recursive call works on a smaller subproblem until a termination condition, called the base case, is reached.
Components of a Recursive Function
Base Case
Stops further recursive calls.
Recursive Case
Function calls itself with modified arguments.
General Form
function_name <- function(parameters)
{
if(base condition)
return(value)
else
return(function_name(smaller_problem))
}
Example 1: Factorial Using Recursion
Mathematically,
with
Program
factorial <- function(n)
{
if(n==0)
return(1)
else
return(n*factorial(n-1))
}
print(factorial(5))
Output
[1] 120
Example 2: Fibonacci Series
with
Program
fib <- function(n)
{
if(n<=1)
return(n)
else
return(fib(n-1)+fib(n-2))
}
print(fib(8))
Output
[1] 21
Example 3: Sum of First n Natural Numbers
sum_n <- function(n)
{
if(n==1)
return(1)
else
return(n+sum_n(n-1))
}
print(sum_n(5))
Output
[1] 15
Example 4: Power Function
power <- function(x,n)
{
if(n==0)
return(1)
else
return(x*power(x,n-1))
}
print(power(2,5))
Output
[1] 32
Comparison of Built-in, User-defined, and Recursive Functions
| Feature | Built-in Function | User-defined Function | Recursive Function |
|---|---|---|---|
| Definition | Provided by R | Created by programmer | Calls itself |
| Availability | Predefined | Must be defined | Must be defined |
| Reusability | High | High | High |
| Complexity | Low | Moderate | High |
| Memory Usage | Low | Low | Higher |
| Examples | sqrt(), sum() | add(), square() | factorial(), fib() |
Advantages of Functions
- Promote modular programming.
- Reduce code duplication.
- Improve readability and maintainability.
- Simplify debugging.
- Enhance reusability.
- Make programs easier to understand and modify.
Summary
Built-in Functions
Predefined functions provided by R for common operations.
Examples:
sqrt(), sum(), mean(), print(), readline()
User-defined Functions
Functions created by programmers to solve specific problems.
Examples:
add(), square(), largest()
Recursive Functions
Functions that call themselves repeatedly until a base condition is satisfied.
Examples:
factorial(), fib(), power()
Conclusion
Functions are one of the most important features of R programming. Built-in functions provide ready-made solutions for common tasks, user-defined functions enable modular and reusable program design, and recursive functions offer elegant solutions to problems that can be expressed in terms of smaller subproblems. Understanding these three types of functions is essential for developing efficient, organized, and maintainable R programs.
Comments
Post a Comment