Type of Functions in R
Overview
Functions in R are sets of statements that serve as essential building blocks in R. We can group a set of instructions and put them inside a function to make our code easier to work with and avoid doing repetitive processes. In this article, we will discuss the types of functions in R.
Introduction
Functions in R allow us to perform various activities, such as manipulating, analyzing, and visualizing data in an organized and systematic way. A function in R is similar to a container that contains a set of code instructions meant to execute a specific task.
Defining a Function in R
We can use the following syntax to define a function:
Now, let us discuss the components of the above function syntax:
- function_name:
It is the official name of the function saved in the R environment as an object with this name. - arguments:
It represents the inputs the function requires to perform its operations. A comma separates each argument and there can be zero or more arguments within a function. - function body:
This is the code block enclosed within curly braces and contains the instructions that the function performs using the provided arguments. - return:
If no inputs are provided, the function returns the value of the last evaluated expression in the code block.
Calling a Function in R
In R, we can invoke a function in three ways:
1. Calling a Function without an Argument:
In R, we can use the function's name followed by parentheses to call it without providing any arguments.
For example:
Output:
Here the hello() function doesn't have any arguments defined. So, when we call the function, it executes the function body and prints, "Hello Everyone".
2. Calling a Function with an Argument:
We have to provide the value for the argument within the function call when invoking a function in R with an argument.
For example:
Output:
Here the hello() function takes one argument name. When we call the function, the value "Scaler" is passed as the argument, and the function will print "Hello Scaler !".
3. Calling a Function with Default Argument:
We can define default values in R for function arguments. The default value will be used whenever an argument is not provided during the function call.
For example:
Output:
Here the hello() function has one argument name with a default value of "All". When we call the function without an argument, it will use the default value and print "Hello All !". If we provide an argument during the function call, it will override the default value and print "Hello, Scaler !".
Types of Functions in R
In R, there are three types of functions:
1. Primitive
Primitive functions are typically written in low-level languages such as C, making them extremely efficient. Unlike regular functions, primitive functions do not have explicit definitions of formals, body, and environment. Instead, they directly call C code to execute specific operations. Due to their close integration with the underlying language, writing and understanding primitive functions can be more complex. However, their efficiency and direct access to low-level operations make them an essential component of R.
We can print the names of the available primitive functions by running the following code in R Console:
Output:
2. Infix
The function name is placed between its arguments for infix functions, resulting in two arguments. Several predefined infix operators exist in R, like +, -, >, etc. Additionally, users can create their infix functions by using names that begin and end with %.
For example:
Output:
Here we created an infix function called power using the %power% operator, which takes two arguments, a and b, and calculates a raise to the power of b using the exponential operator ^.
3. Replacement
Replacement functions modify their arguments in place by avoiding the need for object duplication. They are always succeeded by < in their names and require x and value arguments. More arguments can be added between x and value if necessary.
For example:
Output:
Here we created a vector num with elements 1 to 5. Then we created a replacement function, sqr<- that squares the elements of the given vector.
Built-in Functions in R
R provides different built-in functions for various tasks like generating random numbers, summary statistics, etc. These functions are readily available without requiring any package installations. Here are a few examples of these built-in functions:
- abs(x): It returns the absolute value of input x.
- exp(x): It returns an exponent of input x.
- median(x): It returns the median of input x.
- sum(x): It returns the sum of input x.
- max(x): It returns maximum value of input x.
User-defined Functions in R
User-defined functions allow R users to create their customized functions corresponding to their specific needs. These functions can be created using the function() keyword, followed by the function name and any necessary arguments.
For example:
Output:
We can easily determine whether a given number is even or odd by calling the check() function and providing a specific value for n. The function will then return the result based on the condition applied within the if-else statement.
Higher-Order Functions in R
Higher-order functions accept another function as an argument and perform operations using that function. R provides built-in higher-order functions, such as Reduce, Filter, Map, Find, Position, and Negate, enabling developers to perform powerful data manipulations and transformations.
For example:
Output:
Here, we demonstrated the usage of R's built-in higher-order functions:
- The Reduce() function sums all the elements present in vector num by applying the addition operator (+) in iteration.
- The Filter() function selects only the even numbers from a vector by applying a filtering condition.
- The Map() function calculates the square of each element in a vector.
- The Find() function locates the first even number in a vector by applying a specific condition.
- The Position()function finds the positions of even numbers in a vector based on a given condition.
- The Negate() function combines with the Filter() function to extract the odd numbers from a vector by negating the condition for even numbers.
Conclusion
In conclusion,
- Various functions, including primitive, infix, and replacement functions, are available in R.
- R built-in functions are beneficial to users for common tasks.
- Custom user-defined functions allow for higher personalized functionality.
- Higher-order functions provide more possibilities for advanced programming in R.
Hence, understanding and utilizing these diverse functions in R allows researchers and analysts for effective data analysis, statistical modeling, and visualization.