Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R append() Function - Appending Elements

R append() Function - Appending Elements

R Language Examples R Language Examples

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:

Example

x

<-

c

(

1

,

2

,

3

,

4

,

5

)

Append at the end

result1

<-

append

(

x,

c

(

6

,

7

)

)

print

(

"Append at End:"

)

print

(

result1

)

Insert at a specified position

result2

<-

append

(

x,

c

(

9

,

9

)

, after

=

2

)

print

(

"Insert After the 2nd Element:"

)

print

(

result2

)

Insert at the beginning (after = 0)

result3

<-

append

(

x,

0

, after

=

0

)

print

(

"Insert at Beginning:"

)

print

(

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

)

 

}

}

print

(

"Numbers Divisible by 3:"

)

print

(

result

)

The output of the code above is:

[1] "能被 3 整除的数:"

[1]  3  6  9 12 15 18

R Language Examples R Language Examples