R Functions
A function is a group of statements that together perform a task. The R language itself provides many built-in functions, and of course we can also create our own functions.
You can divide your code into different functions. How you divide the code among different functions is up to you, but logically, the division is usually based on each function performing a specific task.
FunctionDeclarationTells the compiler the function's name, return type, and parameters. FunctionDefinitionProvides the actual body of the function.
In R, a function is an object that can have attributes.
Defining Functions
A function definition usually consists of the following parts:
- Function name:Assigns a unique name to the function for use when calling it.
- Parameters:Define the input values accepted by the function. Parameters are optional and can be multiple.
- Function body:Contains the actual executable code block, using curly braces{}to enclose it.
- Return value:Specifies the output result of the function, using the keyword
return。
Function definitions in R use thefunctionkeyword, the general form is as follows:
function_name <- function(arg_1, arg_2, ...) {
# 函数体
# 执行的代码块
return(output)
}
Description:
- function_name : is the function name
- arg_1, arg_2, ... : the formal parameter list
The function return value usesreturn()。
The following is a simple example showing how to define and use a function:
Example
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 namedadd_numbers, which accepts two parametersxandy. The code in the function body adds the two parameters and stores the result in the variableresult. Finally, use thereturnkeyword to return the result.
To call a function, we use the form of the function name followed by the parameter list to pass the parameter values to the function. In this example, we call theadd_numbersfunction, and pass the arguments 3 and 4. After the function executes, it returns the result 7, which we store in the variablesum_resultand print it out.
User-defined Functions
We can create our own functions for specific functions, and after definition, we can use them like built-in functions.
The following demonstrates how to define a custom function:
Example
new.function <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
Next, we can call the function:
Example
for(i in 1:a) {
b <- i^2
print(b)
}
}
# Call the function and pass the parameters
new.function(6)
Executing the above code, the output result is:
[1] 1 [1] 4 [1] 9 [1] 16 [1] 25 [1] 36
We can also create a function without parameters:
Example
for(i in 1:5) {
print(i^2)
}
}
# Call the function, no need to pass parameters
new.function()
Executing the above code, the output result is:
[1] 1 [1] 4 [1] 9 [1] 16 [1] 25
Functions with Parameter Values
Function parameters can be passed in the order they were created when the function was defined, or out of order, but you need to specify the parameter names:
Example
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)
Executing the above code, the output result is:
[1] 26 [1] 58
When creating a function, you can also specify default values for parameters. If you do not pass parameters when calling, the default values will be used:
Example
new.function <- function(a = 3, b = 6) {
result <- a * b
print(result)
}
# Call the function without passing parameters; it will use the default
new.function()
# Call the function, passing parameters
new.function(9,5)
Executing the above code, the output result is:
[1] 18 [1] 45Lazy Evaluation Functions
Lazy evaluation defers computation until the system needs the results of these calculations. If the results are not needed, the computation will not be performed.
By default, R functions are lazy in computing parameters, meaning they are only called when we compute them:
Example
10
}
f()
Executing the above code, the output result is:
[1] 10
The above code executes without error. Although we did not pass the parameter, the parameter x is not used in the function body, so it is not called and no error is raised.
Example
print(a^2)
print(a)
print(b) # Uses b, but it is not passed, so an error will be raised
}
# Pass one parameter
new.function(6)
Executing the above code, the output result is:
[1] 36 [1] 6 Error in print(b) : 缺少参数"b",也没有缺省值 Calls: new.function -> print 停止执行
Built-in Functions
The 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
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))
Executing the above code, the output result is:
[1] 32 33 34 35 36 37 38 39 40 41 42 43 44 [1] 53.5 [1] 1526
sum(): Calculate the sum of a vector or matrix.
Example
x <- c(1, 2, 3, 4, 5)
total <- sum(x)
print(total) # Output 15
# Sum of a matrix
matrix <- matrix(1:9, nrow = 3)
total <- sum(matrix)
print(total) # Output 45
mean(): Calculate the average of a vector or matrix.
Example
x <- c(1, 2, 3, 4, 5)
avg <- mean(x)
print(avg) # Output 3
# Average of a matrix
matrix <- matrix(1:9, nrow = 3)
avg <- mean(matrix)
print(avg) # Output 5
paste():Concatenate multiple strings into one string.
Example
y <- "World"
result <- paste(x, y)
print(result) # Output "Hello World"
length():Return the length of a vector or the number of elements in an object.
Example
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():Display the structure and content summary of an object.
Example
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 portion of R language function examples. R has a large number of built-in functions and functions provided by extension packages, which can meet various needs such as data processing, statistical analysis, plotting, etc. You can consult the official R language documentation for a more detailed list of functions and usage instructions.
Other Extensions