English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

R Functions

Function is a set of statements that execute together to perform a task. R language itself provides many built-in functions, of course, we can also create our own functions.

You can divide the code into different functions. How to divide the code into different functions is up to you, but in terms of logic, the division is usually based on each function performing a specific task.

FunctionDeclarationInforms the compiler of the function's name, return type, and parameters. FunctionDefineProvide the actual body of the function.

In R language, functions are objects and can have properties.

Define function

In R language, function definition uses the function keyword, and the general form is as follows:

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

Description:

  • function_name : function name

  • arg_1, arg_2, ... : parameter list in the form

The return value of the function uses return().

Built-in function

R language provides many useful built-in functions that we can use directly without defining them.

For example: seq(), mean(), max(), sum(x) and paste(...) and so on.

# Output  32 to 44 all numbers to
print(seq(32,44))
# Calculate the average of two numbers
print(mean(25:82))
# Calculate 41 to 68 Sum of all numbers
print(sum(41:68))

Execute the above code, and the output result is:

 [1] 32 33 34 35 36 37 38 39 40 41 42 43 44
[1] 53.5
[1] 1526

Custom function

We can create our own functions for specific functionalities, and after defining them, we can use them just like built-in functions.

Below is an example of how to define a custom function:

# Define a function to count a series to its square value
new.function <- function(a) {
   for(i in 1:a) {
      b <- i^2
      print(b)
   }
}

Next, we can call the function:

new.function <- function(a) {
    for(i in 1:a) {
       b <- i^2
       print(b)
    }
 }
 
# Call the function and pass the parameters
new.function(6)

Execute the above code, and the output result is:

[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36

We can also create a function without parameters:

new.function <- function() {
    for(i in 1:5) {
        print(i^2)
    }
}       
 
# Call function, do not pass parameters
new.function()

Execute the above code, and the output result is:

[1] 1
[1] 4
[1] 9
[1] 16
[1] 25

Function with Parameter Values

Function parameters can be passed in the order of function creation or not, but parameter names must be specified:

# Create function
new.function <- function(a,b,c) {
   result <- a * b + c
   print(result)
}
# Without parameter name
new.function(5,3,11)
# With parameter name
new.function(a = 11, b = 5, c = 3)

Execute the above code, and the output result is:

[1] 26
[1] 58

When creating a function, default values can also be specified for parameters, and if no parameters are passed in when calling, the default value will be used:

# Create a function with default parameters
new.function <- function(a = 3, b = 6) {
   result <- a * b
   print(result)
}
# Call the function, do not pass the parameter, and use the default
new.function()
# Call the function, pass the parameter
new.function(9,5)

Execute the above code, and the output result is:

[1] 18 [1] 45

Lazy Computation Functions

Lazy computation defers the calculation work until the system needs the results of these calculations. If the results are not needed, the calculation will not be performed.

By default, R functions perform lazy computation, which means they are only called when we calculate them:

f <- function(x) {
  10
}
f()

Execute the above code, and the output result is:

[1] 10

The above code is executed without an error, although we did not pass in any parameters, but the parameter x is not used in the function body, so it will not be called, and no error will occur.

new.function <- function(a, b) {
   print(a^2)
   print(a)
   print(b)  # Use b, but not passed in, so an error will occur
}
# Pass a parameter
new.function(6)

Execute the above code, and the output result is:

[1] 36
[1] 6
Error in print(b) : Missing argument "b", and no default value
Calls: new.function -> print
Stop Execution