R Functions: Define & Call in R Language
In the R language, a function can be defined and called using the following steps:
- purpose
function_name <- function(arg1, arg2, ...) {
# 函数体
}
The function_name is the name of the function, arg1, arg2, … are the parameters of the function, and the function body (#) is the main part of the function, containing the operations the function will perform.
- Calling a function: Use the defined function name and parameters to call the function, with the syntax as follows:
result <- function_name(value1, value2, ...)
The function_name is the name of the function, and value1, value2, … are the specific values of the function’s parameters, with result being the outcome of the function execution.
For example, defining a simple function to calculate the sum of two numbers:
add_numbers <- function(x, y) {
result <- x + y
return(result)
}
Next, call this function.
result <- add_numbers(3, 5)
print(result)
This will output the result 8, indicating that the function add_numbers calculates the sum of 3 and 5 as 8.