R rep() function - Repeat Elements

R 语言实例R Language Examples

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 times each element is repeated individually.

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

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

Parameter description:

  • xThe vector to be repeated.

  • timesThe number of times the entire vector is repeated (or a vector of repetition times for each element individually).

  • eachThe number of times each element is consecutively repeated.

  • length.outThe length of the output result.

Examples

x <- c(1, 2, 3)

# Repeat the entire vector as a whole
print("Repeat the entire vector 3 times:")
print(rep(x, times = 3))

# Specify the number of repetitions for each element individually
print("Repeat each element separately:")
print(rep(x, times = c(2, 1, 3)))

# each: repeat each element in sequence
print("Each element repeated 2 times:")
print(rep(x, each = 2))

# Use each and times in combination
print("each=2, times=2:")
print(rep(x, each = 2, times = 2))

The output of the above code 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 commonly used to create group labels in experimental design:

Examples

# Create 3 treatment groups, each with 5 replicates
treatments <- rep(c("Control group", "Treatment A", "Treatment B"), each = 5)
print("Experimental groups:")
print(treatments)

The output of the above code is:

[1] "实验分组:"
 [1] "对照组" "对照组" "对照组" "对照组" "对照组"
 [6] "处理A"  "处理A"  "处理A"  "处理A"  "处理A"
[11] "处理B"  "处理B"  "处理B"  "处理B"  "处理B"

R 语言实例R Language Examples

Other Extensions