Functions in R Programming (with Example)

In R programming, functions are blocks of code that can be defined and reused to perform specific tasks. Functions are a fundamental concept in R and allow you to modularize your code, improve code organization, and make it more readable. Here’s a brief overview of creating and using functions in R, along with examples:

Defining a Function:

To define a function in R, you use the function() keyword, followed by the function name, arguments, and the code block that implements the function’s behavior. The return() function is used to specify the value that the function should return.

Example: Define a function to calculate the square of a number

square ← function(x) {
result ← x^2

Calling a Function:

Once you’ve defined a function, you can call it by using its name and providing the required arguments.

Call the square function

result ← square(5)
print(result) # Output: 25

Functions with Multiple Arguments:

Functions can take multiple arguments, allowing you to perform more complex operations.

Example: Define a function to calculate the area of a rectangle

rectangle_area ← function(length, width) {
area ← length * width

Call the rectangle_area function

area ← rectangle_area(8, 6)
print(area) # Output: 48

Default Argument Values:

You can provide default values for function arguments, making certain arguments optional.

Example: Define a function with default argument values

power ← function(base, exponent = 2) {
result ← base^exponent

Call the power function

result1 ← power(3)
result2 ← power(2, 4)
print(result1) # Output: 9
print(result2) # Output: 16

Variable-Length Argument Lists:

R allows you to define functions with variable-length argument lists using the … notation.

Example: Define a function with variable-length arguments

mean_custom ← function(…) {
values ← c(…)
avg ← mean(values)

Call the mean_custom function

average ← mean_custom(5, 10, 15)
print(average) # Output: 10