R Functions
A function is a set of statements that perform a task together. The R language itself provides many built-in functions, and of course we can create our own.
You can divide code into different functions. How to divide code into 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. A functiondefineprovides the actual body of the function.
In R, a function is an object and can have attributes.
Defining a function
A function definition usually consists of the following parts:
- **Function name: **assign a unique name to the function so it can be used when called.
- Parameters: Defines the input values the function accepts. Arguments are optional and there can be multiple.
- Function body: Contains the block of code that actually executes, enclosed in curly braces {}.
- **Return value: **specifies the output result of the function, using the keyword
return。
Function definitions in R use the function keyword, with the general form as follows:
function_name <- function(arg_1, arg_2, ...) {
# 函数体
# 执行的代码块
return(output)
}
Explanation:
- function_name : the function name
- arg_1, arg_2, ... : the list of formal arguments
Function return values use return().
The following is a simple example showing how to define and use a function:
Example
Define an addition function
add_numbers
<-
function
(
x, y
)
{
result
<-
x
y
return
(
result
)
}
Calling a function
sum_result
<-
add_numbers
(
3
,
4
)
(
sum_result
)
Output 7
In the code above, we defined a function named add_numbers , which accepts two arguments x and y. The code in the function body adds these two arguments and stores the result in the variable result . Finally, using return keyword to return the result.
To call a function, we use the function name followed by an argument list, passing the argument values to the function. In this example, we call add_numbers function, passing arguments 3 and 4. After execution, it returns the result 7, which we store in the variable sum_result and print it out.
Custom functions
We can create our own functions for specific tasks; once defined, they can be used just like built-in functions.
The following demonstrates how to create a custom function:
Example
Define a function to compute the square of a value in a series
new.
function
<-
function
(
a
)
{
for
(
i
in
1
:
a
)
{
b
<-
i
^
2
(
b
)
}
}
Next we can call the function:
Example
new.
function
<-
function
(
a
)
{
for
(
i
in
1
:
a
)
{
b
<-
i
^
2
(
b
)
}
}
Call the function and pass arguments
new.
function
(
6
)
The output of the code above is:
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36
We can also create a function without arguments:
Example
new.
function
<-
function
(
)
{
for
(
i
in
1
:
5
)
{
(
i
^
2
)
}
}
Call the function; no arguments need to be passed
new.
function
(
)
The output of the code above is:
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
Functions with argument values
Function arguments can be passed in the order in which they were defined, or out of order, but the argument names must be specified:
Example
Define a function
new.
function
<-
function
(
a,b,
c
)
{
result
<-
a
b
c
(
result
)
}
Without argument names
new.
function
(
5
,
3
,
11
)
With argument names
new.
function
(
a
=
11
, b
=
5
,
c
=
3
)
The output of the code above is:
[1] 26
[1] 58
When creating a function, you can also specify default values for arguments; if no argument is passed at call time, the default value is used:
Example
Create a function with default arguments
new.
function
<-
function
(
a
=
3
, b
=
6
)
{
result
<-
a
b
(
result
)
}
Call the function without passing arguments; the default is used
new.
function
(
)
Call the function, passing arguments
new.
function
(
9
,
5
)
The output of the code above is:
[1] 18 [1] 45
Lazy evaluation of functions
Lazy evaluation postpones computation until the system needs the result. If the result is not needed, the computation is not performed.
By default, R functions evaluate arguments lazily, meaning they are only evaluated when we actually use them:
Example
f
<-
function
(
x
)
{
10
}
f
(
)
The output of the code above is:
[1] 10
The above code runs without error; although we did not pass an argument, the function body does not use argument x, so it is never evaluated and no error occurs.
Example
new.
function
<-
function
(
a, b
)
{
(
a
^
2
)
(
a
)
(
b
)
b is used but not passed, so an error occurs
}
Pass an argument
new.
function
(
6
)
The output of the code above is:
[1] 36
[1] 6
Error in print(b) : 缺少参数"b",也没有缺省值
Calls: new.function -> print
停止执行
Built-in functions
R provides many useful built-in functions that we can use directly without defining them.
For example: seq(), mean(), max(), sum(x), and paste(...), among others.
Example
Output all numbers from 32 to 44
(
seq
(
32
,
44
)
)
Calculate the average of two numbers
(
mean
(
25
:
82
)
)
Calculate the sum of all numbers from 41 to 68
(
sum
(
41
:
68
)
)
The output of the code above is:
[1] 32 33 34 35 36 37 38 39 40 41 42 43 44
[1] 53.5
[1] 1526
sum(): calculates the total sum of a vector or matrix.
Example
Sum a vector
x
<-
c
(
1
,
2
,
3
,
4
,
5
)
total
<-
sum
(
x
)
(
total
)
Output 15
Sum a matrix
matrix
<-
matrix
(
1
:
9
,
nrow
=
3
)
total
<-
sum
(
matrix
)
(
total
)
Output 45
mean(): calculates the average of a vector or matrix.
Example
Vector average
x
<-
c
(
1
,
2
,
3
,
4
,
5
)
avg
<-
mean
(
x
)
(
avg
)
Output 3
Matrix average
matrix
<-
matrix
(
1
:
9
,
nrow
=
3
)
avg
<-
mean
(
matrix
)
(
avg
)
Outputs 5
paste(): concatenates multiple strings into one string.
Example
x
<-
"Hello"
y
<-
"World"
result
<-
paste
(
x, y
)
(
result
)
Output "Hello World"
length(): returns the length of a vector or the number of elements in an object.
Example
x
<-
c
(
1
,
2
,
3
,
4
,
5
)
length_x
<-
length
(
x
)
(
length_x
)
Outputs 5
matrix
<-
matrix
(
1
:
9
,
nrow
=
3
)
length_matrix
<-
length
(
matrix
)
(
length_matrix
)
Output 9
str(): displays the structure and a content summary of an object.
Example
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 lists only a small portion of R functions. 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, and plotting. You can consult the official R documentation for a more detailed list of functions and usage instructions.