rep()函數簡介


rep()函數:重復

rep(x,...)

rep.int(x,times)

rep_len(x,length.out)

·x:一個向量(vector),一個因子(factor),一個POSIXct或POSIXlt或Date對象(object)...

·...:更多其他的選項,可能有如下的:

        ·times:必為非負整數,負數或NA是錯誤的。每一個向量重復的次數。

        ·length.out:必為非負整數,缺省或NA是錯誤的。輸出向量期待的輸出長度。

        ·each:必為非負整數,值為1或NA是錯誤的。每一個元素重復each次。

times:同...

length.out:非負整數,輸出向量期待的輸出長度。

例1:

> rep(1:4,2)
[1] 1 2 3 4 1 2 3 4
> rep(1:4,each=2)
[1] 1 1 2 2 3 3 4 4
> rep(1:4,c(2,2,2,2))
[1] 1 1 2 2 3 3 4 4
> rep(1:4,each=2,len=4)
[1] 1 1 2 2
> rep(1:4,each=2,len=10)
 [1] 1 1 2 2 3 3 4 4 1 1
> rep(1:4,each=2,times=3)
 [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

例2:

> rep(1,40*(1-.8))
[1] 1 1 1 1 1 1 1
> 40*(1-.8)
[1] 8
> rep(1,40*(1-.8)+1e-7)
[1] 1 1 1 1 1 1 1 1
> 40*(1-.8)+1e-7
[1] 8

例3:

> #replicate a list
> fred<-list(happy=1:10,name="squash")
> rep(fred,5)
$happy
 [1]  1  2  3  4  5  6  7  8  9 10

$name
[1] "squash"

$happy
 [1]  1  2  3  4  5  6  7  8  9 10

$name
[1] "squash"

$happy
 [1]  1  2  3  4  5  6  7  8  9 10

$name
[1] "squash"

$happy
 [1]  1  2  3  4  5  6  7  8  9 10

$name
[1] "squash"

$happy
 [1]  1  2  3  4  5  6  7  8  9 10

$name
[1] "squash"

例4:

> x<-.leap.seconds[1:3]
> rep(x,2)
[1] "1972-07-01 08:00:00 CST"
[2] "1973-01-01 08:00:00 CST"
[3] "1974-01-01 08:00:00 CST"
[4] "1972-07-01 08:00:00 CST"
[5] "1973-01-01 08:00:00 CST"
[6] "1974-01-01 08:00:00 CST"
> rep(as.POSIXlt(x),rep(2,3))
[1] "1972-07-01 08:00:00 CST"
[2] "1972-07-01 08:00:00 CST"
[3] "1973-01-01 08:00:00 CST"
[4] "1973-01-01 08:00:00 CST"
[5] "1974-01-01 08:00:00 CST"
[6] "1974-01-01 08:00:00 CST"
> rep(as.POSIXct(x),rep(2,3))
[1] "1972-07-01 08:00:00 CST"
[2] "1972-07-01 08:00:00 CST"
[3] "1973-01-01 08:00:00 CST"
[4] "1973-01-01 08:00:00 CST"
[5] "1974-01-01 08:00:00 CST"
[6] "1974-01-01 08:00:00 CST"
> rep(as.Date(x),rep(2,3))
[1] "1972-07-01" "1972-07-01" "1973-01-01"
[4] "1973-01-01" "1974-01-01" "1974-01-01"

例5:

> x<-factor(LETTERS[1:4]);names(x)<-letters[1:4]
> x
a b c d 
A B C D 
Levels: A B C D
> rep(x,2)
a b c d a b c d 
A B C D A B C D 
Levels: A B C D
> rep(x,each=2)
a a b b c c d d 
A A B B C C D D 
Levels: A B C D
> rep.int(x,2)
[1] A B C D A B C D
Levels: A B C D
> rep_len(x,10)
 [1] A B C D A B C D A B
Levels: A B C D

 

 

 

 

 

 

 

 


免責聲明!

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



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