官方幫助文檔如下寫的:
Usage
rep(x, ...) rep.int(x, times) rep_len(x, length.out)
Arguments
x |
a vector (of any mode including a list) or a factor or (for |
... |
further arguments to be passed to or from other methods. For the internal default method these can include:
|
times |
see |
length.out |
non-negative integer: the desired length of the output vector. |
rep函數有4個參數:x向量或者類向量的對象,each:x元素每個重復次數,times:each后的向量的處理,如果times是單個值,則each后的值整體重復times次數,如果是x each后的向量相等長度的向量,則對each后的每個元素重復times同一位置的元素的次數,否則會報錯;length.out指times處理后的向量最終輸出的長度,如果長於生成的向量,則補齊。也就是說rep會先處理each參數,生成一個向量X1,然后times再對X1進行處理生成X2,length.out在對X2進行處理生成最終輸出的向量X3。下面是示例:
> rep(1:4,times=c(1,2,3,4)) #與向量x等長times模式
[1] 1 2 2 3 3 3 4 4 4 4
> rep(1:4,times=c(1,2,3)) #非等長模式,出現錯誤
Error in rep(1:4, times = c(1, 2, 3)) : invalid 'times' argument
> rep(1:4,each=2,times=c(1,2,3,4)) #還是非等長模式,因為each后的向量有8位,而不是4位
Error in rep(1:4, each = 2, times = c(1, 2, 3, 4)) :
invalid 'times' argument
> rep(1:4,times=c(1,2,3,4)) #等長模式,我寫重了o(╯□╰)o
[1] 1 2 2 3 3 3 4 4 4 4
> rep(1:4,times=c(1,2,3,4),each=3) #重復的例子啊,莫拍我
Error in rep(1:4, times = c(1, 2, 3, 4), each = 3) :
invalid 'times' argument
> rep(1:4,each=2,times=1:8) #正確值,times8位長度向量
[1] 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
> rep(1:4,each=2,times=1:8,len=3) #len的使用,循環補齊注意下
[1] 1 1 2
> rep(1:4,each=2,times=3) #先each后times
[1] 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4
>rep函數完畢!