Function The last line of the body of the
functions is automatically
It is a reusable block of code to
returned as output (or can use
performs a specific task.
return()).
It takes input (arguments),
processes it, and gives an output. Example
Types of Functions square = function(x)
{
It is classified into two types:
x*x
o Built-in Functions
}
o User-defined Functions
Built-in Functions
Calling the function:
Functions already available in R.
means using or executing the
Used for common operations. function.
Easy to use and save time. Syntax
Examples: functionname(arguments)
osum() Arguments is called as formal
o mean() arguments
o max() / min() It can be passed by position or by
User-defined Functions name.
Functions created by the user. If the function has no arguments,
empty parentheses () are used.
Used to perform tasks.
Example
Help in reusing code.
Square (4) // passed by position
Creating a Function
Or
using the function() keyword.
Square(x=4) // passed by name
Syntax
Scoping
functionname = function(arguments)
It controls the visibility and lifetime of
{ the variables.
Statements // executable stmts It helps to avoid conflicts between
variable names.
} Variables created inside a function is
called as local variable and it has local
arguments are the inputs given to
scope.
the function.
A local variable can be used only
It is called as formal arguments.
inside the function.
Arguments are optional.
It can have default values.
1
Variables created outside a function is Elements in a list can be given names.
called as global variable and it has Example:
global scope.
student = list (
A global variable can be used inside
and outside the functions. name = "3BCAA",
Scoping Rule age = 20,
grade = “A”
When a variable is used inside a
function, it searches for it inside the )
function. Accessing List Elements
If not found locally, then it searches in
Using double square brackets [[ ]].
the global environment.
This searching order is called Lexical Using $ operator for named lists.
Scoping. Example:
R follows lexical scoping, meaning
student[[1]]
variables are searched based on
where functions are defined. student$name
Accessing Multiple Elements
x = 10 # Global variable
fun = function () Use single square brackets [ ] to
{
return a sub-list.
x=5 # Local variable
print(x) student[1]
}
fun () # Output: 5 Modifying List Elements
print(x)
Elements can be changed or added.
List student$age = 21
It is a collection of elements. student$grade = "B"
All are of different types of elements.
It can contain numbers, characters, Deleting List Elements
vectors, matrices, data frames, or Elements can be removed by assigning
even other lists. NULL.
Creating a List student$grade = NULL
Lists are created using the list() Functions
function. length()
Syntax o Returns the number of
Listname = list(datas) elements in the list.
o length(student)
Example: names()
student = list( "3BCAA",20, “A”)
2
o Returns the names of list
elements.
o names(student)