R(10), Function

Published: by Creative Commons Licence

R language has a large number of built-in functions, but user can also create their own functions.

Function Definition

function_name <- function(arg_1, arg_2, ...) {
   Function body 
}

example:

# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
   for(i in 1:a) {
      b <- i^2
      print(b)
   }
}

Call Functions

which means using function

The parameters of a function call can be provided either in the ordered defined in the function, or in a different order but are assigned to the names of the parameters.

# Create a function with arguments.
new.function <- function(a,b,c) {
   result <- a * b + c
   print(result)
}

# Call the function by position of arguments.
new.function(5,3,11)

# Call the function by names of the arguments.
new.function(a = 11, b = 5, c = 3)

Call functions with default parameters.

# Create a function with arguments.
new.function <- function(a = 3, b = 6) {
   result <- a * b
   print(result)
}

# Call the function without giving any argument.
new.function()

# Call the function with giving new values of the argument.
new.function(9,5)

Delay evaluation of function parameters means that they are evaluated only when the function body needs them.

# Create a function with arguments.
new.function <- function(a, b) {
   print(a^2)
   print(a)
   print(b)
}

# Evaluate the function without supplying one of the arguments.
new.function(6)

result:

[1] 36
[1] 6
Error in print(b) : argument "b" is missing, with no default