R append() Function - Appending Elements
The R append() function is used to insert elements into a vector.
append() can insert new elements at a specified position in a vector, making it more flexible than directly concatenating with c().
The syntax of the append() function is as follows:
append(x, values, after = length(x))
Parameter Description:
-
x The original vector.
-
values The elements to add.
-
after The insertion position (after which index), defaulting to the end.
Example
x
<-
c
(
1
,
2
,
3
,
4
,
5
)
Append at the end
result1
<-
append
(
x,
c
(
6
,
7
)
)
(
"Append at End:"
)
(
result1
)
Insert at a specified position
result2
<-
append
(
x,
c
(
9
,
9
)
, after
=
2
)
(
"Insert After the 2nd Element:"
)
(
result2
)
Insert at the beginning (after = 0)
result3
<-
append
(
x,
0
, after
=
0
)
(
"Insert at Beginning:"
)
(
result3
)
The output of the code above is:
[1] "末尾追加:"
[1] 1 2 3 4 5 6 7
[1] "在第 2 个元素后插入:"
[1] 1 2 9 9 3 4 5
[1] "在开头插入:"
[1] 0 1 2 3 4 5
append() is very useful when building vectors dynamically:
Example
Dynamically collect data that meets a condition
all_numbers
<-
1
:
20
result
<-
c
(
)
Empty vector
for
(
num
in
all_numbers
)
{
if
(
num
%%
3
==
0
)
{
Divisible by 3
result
<-
append
(
result, num
)
}
}
(
"Numbers Divisible by 3:"
)
(
result
)
The output of the code above is:
[1] "能被 3 整除的数:"
[1] 3 6 9 12 15 18
R Language Examples