官方帮助文档如下写的:
Usage
rep(x, ...)
rep.int(x, times)
rep_len(x, length.out)
Arguments
xa vector (of any mode including a list) or a factor or (forreponly) aPOSIXctorPOSIXltorDateobject; or an S4 object containing such an object.
...further arguments to be passed to or from other methods. For the internal default method these can include:
times
A integer vector giving the (non-negative) number of times to repeat each element if of lengthlength(x), or to repeat the whole vector if of length 1. Negative orNAvalues are an error.
length.out
non-negative integer. The desired length of the output vector. Other inputs will be coerced to an integer vector and the first element taken. Ignored ifNAor invalid.
each
non-negative integer. Each element ofxis repeatedeachtimes. Other inputs will be coerced to an integer vector and the first element taken. Treated as1ifNAor invalid.
timessee....
length.outnon-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函数完毕!
网友评论