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

R rep() Function - Repeating Elements

R rep() Function - Repeating Elements

R Language Examples R Language Examples

The R rep() function is used to repeat elements of a vector.

rep() can repeat the whole vector as a unit, or specify repetition counts for each element individually.

The syntax of the rep() function is as follows:

rep(x, times = 1, each = 1, length.out = NA)

Parameter Description:

Example

x

<-

c

(

1

,

2

,

3

)

Repeat as a whole

print

(

"Repeated 3 times as a whole:"

)

print

(

rep

(

x, times

=

3

)

)

Specify repetition counts for each element

print

(

"Each element repeated individually:"

)

print

(

rep

(

x, times

=

c

(

2

,

1

,

3

)

)

)

each: repeat each element in turn

print

(

"Repeat each element 2 times:"

)

print

(

rep

(

x, each

=

2

)

)

Using each and times together

print

(

"each=2, times=2:"

)

print

(

rep

(

x, each

=

2

, times

=

2

)

)

The output of the code above is:

[1] "整体重复 3 次:"

[1] 1 2 3 1 2 3 1 2 3

[1] "每个元素分别重复:"

[1] 1 1 2 3 3 3

[1] "每个元素重复 2 次:"

[1] 1 1 2 2 3 3

[1] "each=2, times=2:"

[1] 1 1 2 2 3 3 1 1 2 2 3 3

rep() is often used to create group labels in experimental designs:

Example

Create 3 treatment groups with 5 replicates each

treatments

<-

rep

(

c

(

"Control group"

,

"Treatment A"

,

"Treatment B"

)

, each

=

5

)

print

(

"Experimental groups:"

)

print

(

treatments

)

The output of the code above is:

[1] "实验分组:"

 [1] "对照组" "对照组" "对照组" "对照组" "对照组"

 [6] "处理A"  "处理A"  "处理A"  "处理A"  "处理A"

[11] "处理B"  "处理B"  "处理B"  "处理B"  "处理B"

R Language Examples R Language Examples