Functions in R Programming
发布时间:2026-09-15 | 浏览:1
R Language Tutorial
Data Structures
Interview Questions
Data Viz. using R
R Data Analysis
R Machine Learning
In R programming, functions are used to organize code into reusable and manageable units. A function accepts input arguments, executes the R commands inside it and produces an output. They are useful when a task needs to be performed multiple times, helping make programs more efficient and easier to understand.
Functions can accept input values, called parameters to work with different data.
They execute the R commands defined inside them and can return a result.
Functions are only executed when they are called, allowing you to control program flow.
In R , you can create custom functions to perform specific tasks by defining a block of code and assigning it a name. Once defined, the function can be called multiple times with different inputs. The function() keyword is used to create a new function in R.
Parameters or Arguments
Functions are used to perform specific tasks and the values they operate on are provided through parameters and arguments. Although these terms are often used interchangeably, they have distinct meanings:
Parameters: Variables that are defined in the function declaration. They act as placeholders for the values the function will use.
Arguments: Actual values passed to the function when it is called. These values replace the parameters during execution.
A function can have multiple parameters and these are separated by commas within the parentheses.
Example: Adding Two Numbers Using a Function
Here we defines a function add_num that takes two numbers as input, adds them and returns the result.
a and b are parameters.
35 and 67 are arguments passed to the function.
Function Parameter Rules
Number of Parameters: A function should be called with the correct number of parameters. If the number doesn't match, an error occurs.
Default Parameter Values : Some functions have default values for parameters. If no argument is passed, these defaults are used.
Return Value: The return() function sends the result back from the function.
Calling a Function
After defining a function, we call it by writing the function name followed by parentheses () and passing the required arguments inside the parentheses.
Case 1: Positional Arguments (Order-Based)
Arguments are passed in the same order as defined in the function
Case 2: Named Arguments (Order Does Not Matter)
Arguments are passed using parameter names, so order is not important.
Case 3: Default Arguments
If no arguments are supplied, the default values defined in the function are used.
Types of Functions in R Language
In R, functions are categorized into two main types:
1. Built-in Functions
Built-in functions are pre-defined functions that come with R. They are ready to use and help perform common mathematical, statistical, data manipulation and file operations.
Example 1 : Using Built-in Functions
Here we use built-in R functions can calculate the sum, maximum and minimum values of a sequence of numbers.
Example 2 : Statistical Built-in Function
Here we creates a numeric vector and calculates its mean and standard deviation using built-in statistical functions in R.
Common Built-in Functions in R
abs(), sqrt(), round(), exp(), log(), cos(), sin(), tan()
mean(), median(), cor(), var(), sd()
Data Manipulation
unique(), subset(), aggregate(), order(), sort()
File Input/Output
read.csv(), write.csv(), read.table(), write.table()
2. User-defined Functions in R
User-defined functions are created by the programmer using the function() keyword. They allow customization of logic, parameters and default values.
Example 1: Even or Odd Function
Here we creates a user defined function that determines whether a number is even or odd and then prints the result for two values.
R Function Examples
Now let's look at some use cases of functions in R with some examples.
1. Single Input Single Output
A function is defined to compute the area of a circle for a given radius and display the result.
2. Multiple Input Multiple Output
In this program, the function accepts two values as input and calculates both the area and perimeter of a rectangle. The results are returned together as a list.
3. Inline Functions
Here inline function is defined in a single line to compute a mathematical expression and the function is evaluated for different input values.
4. Passing Functions as Arguments
In R, a function can be passed as an argument to another function, allowing flexible and reusable code. This supports functional programming by enabling operations to be performed dynamically.
Lazy Evaluations of Functions
Lazy evaluation in R means that function arguments are evaluated only when they are actually used inside the function. If an argument is not required in the computation, the function can still run without it. An error occurs only when a missing argument is used in execution.
Example 1: Unused Argument Does Not Cause Error
Here the argument radius is defined but not used in the calculation, so the function executes successfully even if it is not passed.
Since radius is not used inside the function, R does not evaluate it and no error occurs.
Example 2: Using a Missing Argument Causes Error
Here, the argument radius is used inside the function but not provided during the function call.
Error in Cylinder(5, 10): argument "radius" is missing, with no default
1. Cylinder(5, 10)
2. print(radius)
Because radius is referenced but not supplied, R evaluates it and throws an error.
Related Articles
Function Arguments in R Programming
R Programming Free Course for Beginners
R Programming Exercises, Practice Questions and Solutions
R Programming Language - Introduction 3 min read
Interesting Facts about R Programming Language 4 min read
R vs Python 5 min read
Environments in R Programming 3 min read
Introduction to RStudio 5 min read
How to Install R and R Studio 4 min read
Creation and Execution of R File in R Studio 5 min read
Clear the Console and the Environment in R Studio 2 min read
Hello World in R Programming 2 min read
Basic Syntax in R Programming 3 min read
Comments in R 3 min read
R Operators 5 min read
R-Keywords 2 min read
Data Types in R 5 min read
R Variables - Creating, Naming and Using Variables in R 5 min read
Scope of Variable in R 5 min read
Dynamic Scoping in R Programming 5 min read
Lexical Scoping in R Programming 4 min read
Taking Input from User in R Programming 7 min read
Printing Output of an R Program 4 min read
Print the Argument to the Screen in R Programming - print() Function 2 min read
Control Statements in R Programming 4 min read
Decision Making in R Programming - if, if-else, if-else-if ladder, nested if-else, and switch 3 min read
Switch case in R 2 min read
For loop in R 5 min read
R - while loop 5 min read
R - Repeat loop 2 min read
goto statement in R Programming 2 min read
Break and Next statements in R 3 min read
Functions in R Programming 6 min read
Function Arguments in R Programming 4 min read
Types of Functions in R Programming 6 min read
Recursive Functions in R Programming 4 min read
Conversion Functions in R Programming 4 min read
Data Structures in R Programming 4 min read
R Strings 6 min read
R-Vectors 4 min read
R-Lists 6 min read
R - Array 7 min read
R-Matrices 10 min read
R-Factors 4 min read
R-Data Frames 6 min read
R-Object Oriented Programming 7 min read
Classes in R Programming 3 min read
R-Objects 3 min read
Encapsulation in R Programming 3 min read
Polymorphism in R Programming 6 min read
R - Inheritance 7 min read
Abstraction in R Programming 3 min read
Looping over Objects in R Programming 5 min read
S3 class in R Programming 8 min read
Explicit Coercion in R Programming 3 min read
Handling Errors in R Programming 3 min read
Condition Handling in R Programming 5 min read
Debugging in R Programming 3 min read
File Handling in R Programming 3 min read
Reading Files in R Programming 9 min read
Writing to Files in R Programming 2 min read
Working with Binary Files in R Programming 5 min read
Packages in R Programming 5 min read
Data visualization with ggplot2 in R 8 min read
dplyr Package in R Programming 3 min read
Grid and Lattice Packages in R Programming 3 min read
Shiny Package in R Programming 12 min read
tidyr Package in R Programming 13 min read
Tidyverse Packages in R Language 5 min read
Data Munging in R Programming 11 min read
Data Handling in R Programming 3 min read
Importing Data in R Script 3 min read
Exporting Data from scripts in R Programming 6 min read
Working with CSV files in R Programming 3 min read
Working with XML Files in R Programming 3 min read
Working with Excel Files in R Programming 3 min read
Working with JSON Files in R Programming 4 min read
Working with Databases in R Programming 4 min read
Data Visualization in R 4 min read
R - Line Graphs 3 min read
R - Bar Charts 4 min read
Histograms in R language 2 min read
Scatter plots in R Language 3 min read
R - Pie Charts 3 min read
Boxplots in R Language 4 min read
R - Statistics 2 min read
Mean, Median and Mode in R Programming 2 min read
Descriptive Analysis in R Programming 8 min read
Normal Distribution in R 4 min read
Binomial Distribution in R Programming 3 min read
ANOVA (Analysis of Variance) Test in R Programming 3 min read
Covariance and Correlation in R Programming 3 min read
Skewness in R Programming 3 min read
Hypothesis Testing in R Programming 6 min read
Bootstrapping in R Programming 3 min read
Time Series Analysis in R 3 min read
Introduction to Machine Learning in R 4 min read
Setting up Environment for Machine Learning with R Programming 2 min read
Supervised and Unsupervised Learning in R Programming 3 min read
Regression and its Types in R Programming 5 min read
Classification in R Programming 8 min read
Naive Bayes Classifier in R Programming 4 min read
KNN Classifier in R Programming 4 min read
Clustering in R Programming 10 min read
Decision Tree in R Programming 3 min read
Random Forest Approach in R Programming 5 min read
Hierarchical Clustering in R Programming 4 min read
DBScan Clustering in R Programming 3 min read
Deep Learning in R Programming 5 min read
R Interview Questions with Answers 11 min read
Data Science 360 Course 2 min read
AI Engg Course 2 min read