You are on page 1of 4

Adding Default Value

Default value in a function is a value that is not


required to specify each time the function is called.
Example:
divisible <- function(a, b = 3){
if(a %% b == 0)
{
return(paste(a, "is divisible by", b))
}
else
{ Output:
return(paste(a, "is not divisible by", b))
[1] "10 is divisible by 5"
}
[1] "12 is divisible by 3"
}

# Function call
divisible(10, 5)
divisible(12)
Dots Argument
Dots argument (…) is also known as ellipsis which
allows the function to take an undefined number
of arguments. It allows the function to take an
arbitrary number of arguments.
Calling a Function without an
Argument
# Create a function without an argument.
new.function <- function() { Output:
for(i in 1:5) { [1] 1
[1] 4
print(i^2)
[1] 9
} [1] 16
} [1] 25
# Call the function without supplying an argument.
new.function()
Function as Argument
In R programming, functions can be passed to
another functions as arguments. Below is an
implementation of function as an argument.
Example:
# Function is passed as argument
fun <- function(x, fun2){
return(fun2(x))
}
Output:
# sum is built-in function
fun(c(1:10), sum) [1] 55
[1] 0.2153183
# mean is built-in function
fun(rnorm(50), mean)

You might also like