Types of Functions in R
Function with No Argument, No Return Value
Function with No Argument, With Return Value
Function with Argument, No Return Value
Function with Argument, With Return Value
Function Components
The different parts of a function are −
Function Name
− This is the actual name of the function. It is stored in R environment as an object with this name.Arguments
− An argument is a placeholder. When a function is invoked, you pass a value to the argument. Arguments are optional; that is, a function may contain no arguments. Also arguments can have default values.Function Body
− The function body contains a collection of statements that defines what the function does.Return Value
− The return value of a function is the last expression in the function body to be evaluated.
In [ ]:
function_name = function(arg_1, arg_2, ...)
{
Function body
}
In [8]:
# Create a sequence of numbers from 32 to 44.
print(seq(10))
print(seq(2,10))
print(seq(2,10,2))
# Find mean of numbers from 25 to 82.
print(mean(10:20))
# Find sum of numbers frm 41 to 68.
print(sum(1:10))
[1] 1 2 3 4 5 6 7 8 9 10 [1] 2 3 4 5 6 7 8 9 10 [1] 2 4 6 8 10 [1] 15 [1] 55
In [11]:
Fun=function()
{
print("Hello")
}
Fun()
[1] "Hello"
In [12]:
Fun=function(a)
{
print("Hello")
print(a)
}
Fun(10)
[1] "Hello" [1] 10
In [17]:
Fun=function()
{
print("Hello")
return("Itronix")
}
a=Fun()
print(a)
[1] "Hello" [1] "Itronix"
In [18]:
Fun=function(a)
{
print("Hello")
print(a)
return(20)
}
a=Fun(10)
print(a)
[1] "Hello" [1] 10 [1] 20
In [19]:
Fun = function(a,b,c)
{
result = a * b + c
print(result)
}
Fun(5,3,11)
Fun(a = 11, b = 5, c = 3)
[1] 26 [1] 58
In [20]:
Fun = function(a=10,b=6)
{
result = a * b
print(result)
}
Fun()
Fun(a = 11, b = 5)
[1] 60 [1] 55
In [3]:
Add=function(a,b)
{
result=a+b
print(result)
return(a+b)
}
Fact=function(n)
{
f=1
for(i in 1:n)
{
f=f*i
}
print(f)
}
c=Add(3,2)
Fact(c)
[1] 5 [1] 120
In [ ]: