📜  在 R 中创建重复值序列(1)

📅  最后修改于: 2023-12-03 15:23:16.980000             🧑  作者: Mango

在 R 中,我们可以使用 rep() 函数来创建重复值序列。该函数的语法如下:

rep(x, times, each, length.out)

其中,x 表示要重复的向量或标量,times 表示重复的次数,each 表示每个元素重复的次数,length.out 表示生成的序列的长度。

下面是一些示例:

1. 重复向量
# 重复向量 c(1, 2, 3) 3 次
rep(c(1, 2, 3), times = 3)
#> [1] 1 2 3 1 2 3 1 2 3

# 重复向量 c("a", "b", "c") 2 次
rep(c("a", "b", "c"), times = 2)
#> [1] "a" "b" "c" "a" "b" "c"

# 重复标量 "hello" 5 次
rep("hello", times = 5)
#> [1] "hello" "hello" "hello" "hello" "hello"
2. 每个元素重复多次
# 重复向量 c(1, 2, 3) 每个元素 2 次
rep(c(1, 2, 3), each = 2)
#> [1] 1 1 2 2 3 3

# 重复向量 c("a", "b", "c") 每个元素 3 次
rep(c("a", "b", "c"), each = 3)
#> [1] "a" "a" "a" "b" "b" "b" "c" "c" "c"

# 重复标量 "hello" 每个元素 4 次
rep("hello", each = 4)
#> [1] "hello" "hello" "hello" "hello"
3. 指定生成的序列长度
# 重复向量 c(1, 2, 3) 5 次,生成长度为 10 的序列
rep(c(1, 2, 3), length.out = 10)
#>  [1] 1 2 3 1 2 3 1 2 3 1

# 重复向量 c("a", "b") 3 次,生成长度为 7 的序列
rep(c("a", "b"), length.out = 7)
#> [1] "a" "b" "a" "b" "a" "b" "a"

# 重复标量 "hello" 2 次,生成长度为 8 的序列
rep("hello", length.out = 8)
#> [1] "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello"

以上是 rep() 函数的三种用法,通过不同的参数组合可以生成不同的重复值序列。在实际工作中,我们常常需要创建重复值序列来生成测试数据、填充缺失值等。