R中rep函數的使用


官方幫助文檔如下寫的:

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 rep only) a POSIXct or POSIXlt or Date object; 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 length length(x), or to repeat the whole vector if of length 1. Negative or NA values 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 if NA or invalid.

each

non-negative integer. Each element of x is repeated each times. Other inputs will be coerced to an integer vector and the first element taken. Treated as 1 if NA or invalid.

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函數完畢!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM