R Functions

  • Functions are set of statements organized to perform a specific task.
  • R has large number of built-in functions.
  • R allows users to create their own function. These functions are called user defined functions.
  • R Functions are created using ‘function’ keyword.

Syntax:

function_name <- function(arg_1, arg_2, …) expression

Example: Create function to add given two numbers.

Calling a function Arguments

> addition<-function(x,y) { #x,y are arguments + z=x+y + print(z) } > addition(2,3) # Calling function with argument [1] 5

Calling a function Arguments

details<-function(name,age){ print(paste("Hello ",name,"Your age is ",age)) } details("Vijay",10) # Passing arguments

Calling a function without an Arguement

powerof<-function(){ for(k in 1:10){ print(k**2) } } powerof() #Calling a function without an Arguement [1] 1 [1] 4 [1] 9 [1] 16 [1] 25 [1] 36 [1] 49 [1] 64 [1] 81 [1] 100

Calling a function with default Argument:If we assign arguments at the time of declaration, a function can called with or without arguments.

multiplication<-function(x=10,y=20){ multi<-x*y print(multi) } multiplication() #This will take default values multiplication(5,6) #This will not perform on default values

Powered by WordPress