使用 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