R Func Rep
# R rep() Function - Repeat Elements
[ R Language Examples](#)
The R rep() function is used to repeat elements in a vector.
rep() can repeat the entire vector as a whole, or specify the number of repetitions for each element individually.
The syntax format of the rep() function is as follows:
rep(x, times = 1, each = 1, length.out = NA)
**Parameter Description:**
* **x** The vector to be repeated.
* **times** The number of times the entire vector is repeated (or a vector specifying the number of repetitions for each element individually).
* **each** The number of consecutive repetitions for each element.
* **length.out** The length of the output result.
## Example
x <-c(1, 2, 3)
# Repeat as a whole
print("Repeat as a whole 3 times:")
print(rep(x, times =3))
# Specify the number of repetitions for each element individually
print("Repeat each element 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))
# Combine each and times
print("each=2, times=2:")
print(rep(x, each =2, times =2))
Executing the above code outputs the following result:
"Repeat as a whole 3 times:" 1 2 3 1 2 3 1 2 3 "Repeat each element individually:" 1 1 2 3 3 3 "Repeat each element 2 times:" 1 1 2 2 3 3 "each=2, times=2:" 1 1 2 2 3 3 1 1 2 2 3 3
rep() is commonly used to create grouping labels in experimental designs:
## Example
# Create 3 treatment groups, 5 replicates per group
treatments <-rep(c("Control Group", "Treatment A", "Treatment B"), each =5)
print("Experimental grouping:")
print(treatments)
Executing the above code outputs the following result:
"Experimental grouping:" "Control Group" "Control Group" "Control Group" "Control Group" "Control Group" "Treatment A" "Treatment A" "Treatment A" "Treatment A" "Treatment A" "Treatment B" "Treatment B" "Treatment B" "Treatment B" "Treatment B"
[![Image 4: R Language Examples
YouTip