0% found this document useful (0 votes)
1 views16 pages

Functions in R Programming

The document provides a comprehensive overview of functions in R programming, including how to create, call, and use both built-in and user-defined functions. It explains the concepts of parameters, arguments, and lazy evaluation, as well as the principles of lexical scoping. Additionally, it covers date and time functions in R, highlighting various methods for handling date-time operations.

Uploaded by

melbamelba1996
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views16 pages

Functions in R Programming

The document provides a comprehensive overview of functions in R programming, including how to create, call, and use both built-in and user-defined functions. It explains the concepts of parameters, arguments, and lazy evaluation, as well as the principles of lexical scoping. Additionally, it covers date and time functions in R, highlighting various methods for handling date-time operations.

Uploaded by

melbamelba1996
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Functions in R Programming

Last Updated : 12 Jul, 2025



A function accepts input arguments and produces the output by executing


valid R commands that are inside the function. Functions are useful when we
want to perform a certain task multiple times.
In R Programming Language when we are creating a function the function
name and the file in which we are creating the function need not be the same
and we can have one or more functions in R.
Creating a Function in R Programming
Functions are created in R by using the command function(). The general
structure of the function file is as follows:

Functions in R
Programming
Note: In the above syntax f is the function name, this means that we are
creating a function with name f which takes certain arguments and executes
the following statements.
Parameters or Arguments in R Functions
In programming, parameters and arguments refer to the values passed into a
function. They are often used interchangeably, but there is a subtle difference:
 Parameters are the variables defined in the function definition.
 Arguments are the actual values passed to the function when it is called.
A function can have multiple parameters, and these are separated by commas
within the parentheses.
Example:
add_num <- function(a,b)
{
sum_result <- a+b
return(sum_result)
}

sum = add_num(35,34)

print(sum)
Output
[1] 69
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.
Read More: R Function Parameters

Calling a Function in R
After creating a Function, we have to call the function to use it. Calling a
function in R is done by writing it's name and passing possible parameters
value.
Passing Arguments to Functions in R Programming Language
There are several ways we can pass the arguments to the function:
 Case 1: Generally in R, the arguments are passed to the function in the
same order as in the function definition.
 Case 2: If we do not want to follow any order what we can do is we can
pass the arguments using the names of the arguments in any order.
 Case 3: If the arguments are not passed the default values are used to
execute the function.
Now, let us see the examples for each of these cases in the following R code:
Rectangle = function(length=5, width=4){
area = length * width
return(area)
}

# Case 1:
print(Rectangle(2, 3))

# Case 2:
print(Rectangle(width = 8, length = 4))
# Case 3:
print(Rectangle())

Output
[1] 6
[1] 32
[1] 20

Types of Function in R Language


1. Built-in Function: Built-in functions in R are pre-defined functions that are
available in R programming languages to perform common tasks or
operations.
2. User-defined Function: R language allow us to write our own function.
1. Built-in Function in R Programming Language
Built-in Function are the functions that are already existing in R language and
we just need to call them to use.
Here we will use built-in functions like sum(), max() and min().
print(sum(4:6))

print(max(4:6))

print(min(4:6))
Output
[1] 15
[1] 6
[1] 4
Other Built-in Functions in R
Let's look at the list of built-in R functions and their uses:
Category Function

Mathematical abs(), sqrt(), round(), exp(), log(), cos(), sin(), tan(


Functions )

Statistical Functions mean(), median(), cor(), var()

Data Manipulation
unique(), subset(), aggregate(), order()
Functions
Category Function

File Input/Output
[Link](), [Link](), [Link](), [Link]()
Functions

2. User-defined Functions in R Programming


Language
User-defined functions are the functions that are created by the user. The
User defines the working, parameters, default parameter, etc. of that user-
defined function. They can be only used in that specific code.
evenOdd = function(x){
if(x %% 2 == 0)
return("even")
else
return("odd")
}

print(evenOdd(4))
print(evenOdd(3))
Output
[1] "even"
[1] "odd"

R Function Examples
Now let's look at some use cases of functions in R with some examples.
1. Single Input Single Output
Create a function that takes a single input and returns a single output. For
example, a function to calculate the area of a circle:
areaOfCircle = function(radius){
area = pi*radius^2
return(area)
}

print(areaOfCircle(2))

Output
[1] 12.56637

2. Multiple Input Multiple Output


Create a function that takes multiple inputs and returns multiple outputs using
a list. For example, a function to calculate the area and perimeter of a
rectangle:
Rectangle = function(length, width){
area = length * width
perimeter = 2 * (length + width)

result = list("Area" = area, "Perimeter" = perimeter)


return(result)
}

resultList = Rectangle(2, 3)
print(resultList["Area"])
print(resultList["Perimeter"])

Output
$Area
[1] 6

$Perimeter
[1] 10

3. Inline Functions in R Programming Language


For small, quick functions, use inline functions. These are defined directly in
the expression.
f = function(x) x^2*4+x/3

print(f(4))
print(f(-2))
print(0)

Output
[1] 65.33333
[1] 15.33333
[1] 0

Lazy Evaluations of Functions in R Programming


Language
In R, functions are executed lazily, meaning that if some arguments are
missing, the function still executes as long as those arguments are not
involved in the execution. For example, consider the following function
Cylinder, which calculates the volume of a cylinder using diameter and length.
The argument radius is defined but not used in the calculation.
Even if we don't pass the radius, the function will still execute because it
doesn't affect the volume calculation.
Cylinder = function(diameter, length, radius ){
volume = pi*diameter^2*length/4
return(volume)
}

print(Cylinder(5, 10))

Output
[1] 196.3495
If we do not pass the argument and then use it in the definition of the function
it will throw an error that this "radius" is not passed and it is being used in the
function definition.
Example
Cylinder = function(diameter, length, radius ){
volume = pi*diameter^2*length/4
print(radius)
return(volume)
}

print(Cylinder(5, 10))
Output
Error in print(radius) : argument "radius" is missing, with no default
We have discussed all about R functions to give we some idea about using
functions in R language. we can go and study each individual in-built function
on this page to completely grasp the concept of R functions and their uses.

Lexical Scoping in R Programming


Last Updated : 16 Apr, 2025



Lexical scoping means R decides where to look for a variable based on


where the function was written (defined), not where it is called.
When a function runs and it sees a variable, R checks:
 Inside the function, is the variable there?
 If not, it looks in the environment where the function was created.
 Then it keeps moving up — one level at a time — until it finds the variable
or reaches the global environment.
Consider the following example:
f <- function(x, y)
{
x * y * z
}
In this:
 x and y are formal arguments
 z as the free variable
Therefore, the scoping rules of the language determine how values are
assigned to free variables. Free variables are not formal arguments and not
local variables that are assigned inside of the function body.
Principles of Lexical Scoping
There are four basic principles behind R’s implementation of lexical scoping:
1. Name Masking
2. Functions vs variables
3. A fresh start
4. Dynamic Lookup
Let's discuss each principle one by one.
Name Masking
The following example illustrates the most basic principle of lexical scoping,
and you should have no problem predicting the output.
If variable is not defined inside the function:
Example:
c <- 10
f <- function(a, b)
{
a + b + c
}
f(8, 5)

Output
[1] 23
It takes the c value as 10 and then adds these numbers and finally we are
having 23 as output.
If name is not defined inside the function: If a name isn’t defined inside a
function, R will look one level up. Example:
a <- 10
b <- function()
{
c <- 11
c(a, c)
}
b()

Output
[1] 10 11
When one function is defined inside another function:
The same rules apply if a function is defined inside another function: look
inside the current function, then where that function was defined, and so on,
all the way up to the global environment, and then on to other loaded
packages. Example:
a <- 10
g <- function(){
b <- 20
h <- function(){
c <- 30
c(a, b, c)
}
h()
}
g()

Output
[1] 10 20 30
When functions are created by another function:
The same rules apply to closures, functions created by other
functions. Example:
a <- function(z){
b <- 10
function(){
z + 4 * b
}
}
x <- a(10)
x()

Output
[1] 50
R returns the accurate value of b after calling the function because x
preserves the environment in which it was defined. The environment
includes the value of b.
Functions vs Variables
The same principles apply regardless of the type of associated value —
finding functions works exactly the same way as finding variables:
Example:
a <- function(x) 10 * x
b <- function(){
a <- function(x) x + 10
a(12)
}
b()

Output
[1] 22

A Fresh Start
When a function is called, a new environment is created every time. Each
acknowledgement is completely independent because a function cannot tell
what happened when it was run last time.
Example:
a <- function(){
if(!exists("z"))
{
z <- 10
}
else
{
z <- z+10
}
z
}
a()

Output
[1] 10

Dynamic Lookup
Lexical scoping controls where to look for values not when to look for them.
R looks for the values when the function is executed not when it is created.
The output of the function can be different depending on objects outside its
environment.
Example:
g <- function() x^3
x <- 10
g()

Output
[1] 1000
There is a function in R which is findGlobals() from codetools and it helps
us to find all global variables being used in a function and lists all the
external dependencies of a function. findGlobals() find the global variables
and functions which are used by the closure. Example:
aGlobal <- rnorm(10)
bGlobal <- rnorm(10)

f <- function()
{
a <- aGlobal
b <- bGlobal
plot(b ~ a)
}
codetools::findGlobals(f)

Output
[1] "{" "<-" "~" "aGlobal" "bGlobal" "plot"
We can manually change the environment to the empty
environment emptyenv(). emptyenv() is a totally empty environment.

Get Date and Time in different Formats in R


Programming - date(), [Link](), [Link]()
and [Link]() Function


function in R Language is used to return the current date and time.


date()
Syntax: date() Parameters: Does not accept any parameters

Example:
# R program to illustrate
# date function

# Calling date() function to


# return current date and time
date()
Output:
[1] "Thu Jun 11 04:29:39 2020"
[Link]() Function
[Link]() function is used to return the system's date.

Syntax: [Link]() Parameters: Does not accept any parameters


Example:
# R program to illustrate
# [Link] function

# Calling [Link]() function to


# return the system's date
[Link]()
Output:
[1] "2020-06-11"
[Link]()
[Link]() function is used to return the system's date and time.

Syntax: [Link]() Parameters: Does not accept any parameters

Example:
# R program to illustrate
# [Link] function

# Calling [Link]() function to


# return the system's date and time
[Link]()
Output:
[1] "2020-06-11 05:35:49 UTC"
[Link]()
[Link]() function is used to return the current time zone.

Syntax: [Link]() Parameters: Does not accept any parameters

Example:
# R program to illustrate
# [Link] function

# Calling [Link]() function to


# return the current time zone
[Link]()
Output:
[1] "Etc/UTC"
strptime() function in R Language is used to parse the given representation of
date and time with the given template.

Syntax: strptime(x, format, tz = "")


Parameters:
x: given representation of date and time
y: given template in which parsing is done
tz: a character string specifying the time zone to be used for the conversion

Example 1:

# R program to illustrate
# strptime function

# Specifying a time
x <- "13:15:17"

# Calling strptime() function


# over specified time and template
y <- strptime(x, "% H:% M:% S")

# Getting the current date and


# given time into specified template
y
Output:

[1] "2020-06-17 13:15:17 UTC"


R offers several ways to perform operations on dates and times, primarily
through base R functions and the lubridate package.

1. Base R Functions:
 Creating Date/Time Objects:
 [Link](): Converts character strings to Date objects (e.g., "YYYY-MM-DD").
 [Link]() and [Link](): Convert character strings or other formats
to POSIXct (timestamp) or POSIXlt (list of components) objects for handling dates and
times with time zone information.
 Getting Current Date/Time:
 [Link](): Returns the current system date.
 [Link](): Returns the current system date and time.
 Arithmetic Operations:
 Subtracting two Date or POSIXct objects yields a difftime object, representing the
time difference.
 Adding or subtracting numeric values to Date or POSIXct objects can add/subtract
days or seconds, respectively.
 Formatting and Extraction:
 format(): Formats date/time objects into specific character strings.
 weekdays(), months(), quarters(), years(): Extract specific components
from Date objects.
 Time Differences:
 difftime(): Calculates the difference between two date-time objects in specified units
(e.g., "days", "hours").
2. lubridate Package:

The lubridate package simplifies and enhances date-time operations.


 Parsing Dates and Times:
 Functions like ymd(), mdy(), dmy(), ymd_hms() efficiently parse various date-time string
formats.
 Extracting Components:
 year(), month(), day(), hour(), minute(), second(), wday() (weekday), yday() (day of
year) directly extract components.
 Arithmetic and Manipulation:
 +and - operators work intuitively with Period and Duration objects for
adding/subtracting time units (e.g., days(5), hours(2)).
 interval(): Creates an interval between two date-times, allowing for operations like
checking if a date falls within an interval.
 Time Zones:
 with_tz(): Changes the time zone of a date-time object without changing the
underlying instant in time.
 force_tz(): Changes the time zone while keeping the clock time the same.

1. Vectors
A vector is an ordered collection of basic data types of a given length. The
only key thing here is all the elements of a vector must be of the identical
data type e.g homogeneous data structures. Vectors are one-dimensional
data structures.
Example:
X = c(1, 3, 5, 7, 8)

print(X)
Output:
[1] 1 3 5 7 8

2. Lists
A list is a generic object consisting of an ordered collection of objects. Lists
are heterogeneous data structures. These are also one-dimensional data
structures. A list can be a list of vectors, list of matrices, a list of characters
and a list of functions and so on.
Example:
empId = c(1, 2, 3, 4)

empName = c("Debi", "Sandeep", "Subham", "Shiba")

numberOfEmp = 4

empList = list(empId, empName, numberOfEmp)

print(empList)
Output:

Lists
3. Data Frames
Data frames are generic data objects of R which are used to store the
tabular data. Data frames are the foremost popular data objects in R
programming because we are comfortable in seeing the data within the
tabular form. They are two-dimensional, heterogeneous data structures.
These are lists of vectors of equal lengths.
Data frames have the following constraints placed upon them:
 A data-frame must have column names and every row should have a
unique name.
 Each column must have the identical number of items.
 Each item in a single column must be of the same data type.
 Different columns may have different data types.
To create a data frame we use the [Link]() function.
Example:
Name = c("Amiya", "Raj", "Asish")
Language = c("R", "Python", "Java")
Age = c(22, 25, 45)

df = [Link](Name, Language, Age)

print(df)
Output:

Data Frames
4. Matrices
A matrix is a rectangular arrangement of numbers in rows and columns. In a
matrix, as we know rows are the ones that run horizontally and columns are
the ones that run vertically. Matrices are two-dimensional, homogeneous
data structures.
Example:
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3, ncol = 3,
byrow = TRUE
)

print(A)
Output:

Matrix
5. Arrays
Arrays are the R data objects which store the data in more than two
dimensions. Arrays are n-dimensional data structures. For example, if we
create an array of dimensions (2, 3, 3) then it creates 3 rectangular matrices
each with 2 rows and 3 columns. They are homogeneous data structures.
Example:
A = array(
c(1, 2, 3, 4, 5, 6, 7, 8),
dim = c(2, 2, 2)
)

print(A)
Output:

Arrays
6. Factors
Factors are the data objects which are used to categorize the data and store
it as levels. They are useful for storing categorical data. They can store both
strings and integers. They are useful to categorize unique values in columns
like (“TRUE” or “FALSE”) or (“MALE” or “FEMALE”), etc.. They are useful in
data analysis for statistical modeling.
Example:
# Creating factor using factor()
fac = factor(c("Male", "Female", "Male",
"Male", "Female", "Male", "Female"))

print(fac)
Output:
[1] Male Female Male Male Female Male Female
Levels: Female Male

You might also like