What is Functions in R?

Description

To understand the functions available in R,how to define a function and call the same.

    • Functions are block of codes that performs a specified task.Types of functions available in R User defined functions
    • Built-in functions

User defined functions :
Syntax :

Function_name<-function(arg1,arg2,…)

{

Function body

Return()

}

Function arguments and return value :

  • Function may or may not return a value
  • Function may or may not have arguments
  • Function can also have default arguments

Source code :(User-defined functions)

add<-function(a,b)
{
sum=a+b
cat(“Sum of a and b is “,sum)
}
sub<-function(a,b)
{
diff=a-b
cat(“Difference of b from a is “,diff)
}
mul<-function(a,b)
{
product=a*b
cat(“Product of a and b is “,product)
}
div<-function(a,b)
{
quo=a/b
cat(“Quotient from a/b is “,quo)
}
x=as.integer(readline(prompt=”Enter your choice\n 1.Addition\n 2.Subtraction\n 3.Multiplication\n 4.Division\n”))
a=as.integer(readline(prompt=”Enter a value “))
b=as.integer(readline(prompt=”Enter b value “))
switch(x,add(a,b),sub(a,b),mul(a,b),div(a,b))

Source code :(Function arguments and return values)

add<-function()
{
a=5
b=10
c=a+b
return(c) #Function with return value
}
sub<-function(a,b)
{
c=a-b
return(c)
}
mul<-function(a=5,b=10)
{
return(a*b)
}
cat(“Addition “,add())
cat(“\nSubtraction “,sub(10,5))
cat(“\nProduct “,mul())
cat(“\nProduct “,mul(a=100,b=10))

Leave Comment

Your email address will not be published. Required fields are marked *

clear formSubmit