使用 rep() 函数扩展向量

rep 函数可用于以相当灵活的方式重复向量。

# repeat counting numbers, 1 through 5 twice
rep(1:5, 2)
[1] 1 2 3 4 5 1 2 3 4 5

# repeat vector with incomplete recycling
rep(1:5, 2, length.out=7)
[1] 1 2 3 4 5 1 2

每个参数对于将观测/实验单位的统计向量扩展为 data.frame 的向量以及对这些单元的重复观察特别有用。

# same except repeat each integer next to each other
rep(1:5, each=2)
[1] 1 1 2 2 3 3 4 4 5 5

关于涉及扩展到这种数据结构的 rep 的一个很好的特性是,可以通过用一个向量替换长度参数来实现向量向不平衡面板的扩展,该向量决定了向量中重复每个元素的次数:

# automated length repetition
rep(1:5, 1:5)
 [1] 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
# hand-fed repetition length vector
rep(1:5, c(1,1,1,2,2))
[1] 1 2 3 4 4 5 5

这应该暴露允许外部函数提供 rep 的第二个参数的可能性,以便动态地构造根据数据扩展的向量。

seq 一样,rep 的更快,简化版本是 rep_lenrep.int。这些删除了 rep 维护的一些属性,因此在速度受到关注的情况下可能最有用,并且重复向量的其他方面是不必要的。

# repeat counting numbers, 1 through 5 twice
rep.int(1:5, 2)
[1] 1 2 3 4 5 1 2 3 4 5

# repeat vector with incomplete recycling
rep_len(1:5, length.out=7)
[1] 1 2 3 4 5 1 2