R rep() Function - Repeating Elements
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:
-
x The vector to repeat.
-
times The number of times to repeat the whole vector (or a vector of repetition counts for each element).
-
each The number of times each element is repeated consecutively.
-
length.out The length of the output result.
Example
x
<-
c
(
1
,
2
,
3
)
Repeat as a whole
(
"Repeated 3 times as a whole:"
)
(
rep
(
x, times
=
3
)
)
Specify repetition counts for each element
(
"Each element repeated individually:"
)
(
rep
(
x, times
=
c
(
2
,
1
,
3
)
)
)
each: repeat each element in turn
(
"Repeat each element 2 times:"
)
(
rep
(
x, each
=
2
)
)
Using each and times together
(
"each=2, times=2:"
)
(
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
)
(
"Experimental groups:"
)
(
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