R Functions
π
2026-06-23 | π R
R Functions | R Tutorial
A function is a group of statements that together perform a task. R language provides many built-in functions, and of course we can also create our own functions.
You can divide your code into different functions. How to divide the code into different functions is up to you, but logically, the division is usually based on each function performing a specific task.
A function **declaration** tells the compiler the function's name, return type, and parameters. A function **definition** provides the actual body of the function.
In R language, a function is an object that can have properties.
A function definition generally consists of the following parts:
* **Function Name:** Assigns a unique name to the function for use when calling it.
* **Parameters:** Define the input values that the function accepts. Parameters are optional and there can be multiple.
* **Function Body:** Contains the actual code to be executed, enclosed in curly braces {}.
* **Return Value:** Specifies the output result of the function, using the `return` keyword.
Function definitions in R language use the function keyword, generally as follows:
```r
function_name <- function(arg_1, arg_2, ...) {
# Function Body
# Code block to execute
return(output)
}
Note:
* `function_name`: The function name
* `arg_1, arg_2, ...`: The list of formal parameters
Function return values use `return()`.
The following is a simple example showing how to define and use a function:
## Example
```r
# Define an addition function
add_numbers <- function(x, y) {
result <- x + y
return(result)
}
# Call the function
sum_result <- add_numbers(3, 4)
print(sum_result) # Output 7
In the above code, we defined a function named **add_numbers**, which accepts two parameters **x** and **y**. The code in the function body adds these two parameters together and stores the result in the variable **result**. Finally, we use the **return** keyword to return the result.
To call a function, we use the function name followed by the parameter list, passing the values of the parameters to the function. In this example, we call the **add_numbers** function and pass parameters 3 and 4. After the function executes, it returns the result 7, which we store in the variable **sum_result** and print out.
### Custom Functions
We can create our own functions for specific purposes, and after defining them, we can use them just like built-in functions.
The following demonstrates how to define custom functions:
## Example
```r
# Define a function to calculate the square values of a series
new.function <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
Next, we can call the function:
## Example
```r
new.function <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
# Call the function and pass parameters
new.function(6)
After executing the above code, the output is:
1
4
9
16
25
36
We can also create a function without parameters:
## Example
```r
new.function <- function() {
for(i in 1:5) {
print(i^2)
}
}
# Call the function, no need to pass parameters
new.function()
After executing the above code, the output is:
1
4
9
16
25
### Functions with Parameter Values
Function parameters can be passed in the order they were defined in the function, or out of order, but the parameter names must be specified:
## Example
```r
# Create a function
new.function <- function(a, b, c) {
result <- a * b + c
print(result)
}
# Without parameter names
new.function(5, 3, 11)
# With parameter names
new.function(a = 11, b = 5, c = 3)
After executing the above code, the output is:
26
58
When creating a function, you can also specify default values for parameters. If no parameters are passed during the call, the default values will be used:
## Example
```r
# Create a function with default parameters
new.function <- function(a = 3, b = 6) {
result <- a * b
print(result)
}
# Call the function without passing parameters, will use defaults
new.function()
# Call the function with parameters passed
new.function(9, 5)
After executing the above code, the output is:
18
45
### Lazy Evaluation Functions
Lazy evaluation defers computation work until the system needs the results of these computations. If the results are not needed, the computation will not be performed.
By default, R functions have lazy evaluation of parameters, meaning they are only evaluated when we actually compute them:
## Example
```r
f <- function(x) {
10
}
f()
After executing the above code, the output is:
10
The above code executes without error. Although we did not pass a parameter, the parameter x is not used in the function body, so it is not evaluated, and no error occurs.
## Example
```r
new.function print
Execution halted
* * *
## Built-in Functions
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(...), etc.
## Example
```r
# Output all numbers from 32 to 44
print(seq(32, 44))
# Calculate the average of two numbers
print(mean(25:82))
# Calculate the sum of all numbers from 41 to 68
print(sum(41:68))
After executing the above code, the output is:
32 33 34 35 36 37 38 39 40 41 42 43 44
53.5
1526
sum(): Calculates the sum of a vector or matrix.
## Example
```r
# Vector sum
x <- c(1, 2, 3, 4, 5)
total <- sum(x)
print(total) # Output 15
# Matrix sum
matrix <- matrix(1:9, nrow = 3)
total <- sum(matrix)
print(total) # Output 45
mean(): Calculates the average of a vector or matrix.
## Example
```r
# Vector average
x <- c(1, 2, 3, 4, 5)
avg <- mean(x)
print(avg) # Output 3
# Matrix average
matrix <- matrix(1:9, nrow = 3)
avg <- mean(matrix)
print(avg) # Output 5
paste(): Concatenates multiple strings into one string.
## Example
```r
x <- "Hello"
y <- "World"
result <- paste(x, y)
print(result) # Output "Hello World"
length(): Returns the length of a vector or the number of elements in an object.
## Example
```r
x <- c(1, 2, 3, 4, 5)
length_x <- length(x)
print(length_x) # Output 5
matrix <- matrix(1:9, nrow = 3)
length_matrix <- length(matrix)
print(length_matrix) # Output 9
str(): Displays the structure and content summary of an object.
## Example
```r
x <- c(1, 2, 3, 4, 5)
str(x)
# Output:
# num [1:5] 1 2 3 4 5
matrix <- matrix(1:9, nrow = 3)
str(matrix)
# Output:
# int [1:3, 1:3] 1 2 3 4 5 6 7 8 9
The above only lists a small number of R language function examples. R has a large number of built-in functions and functions provided by packages, which can meet various needs for data processing, statistical analysis,