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: timesA 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. 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. 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函數(shù)有4個(gè)參數(shù):x向量或者類向量的對象,each:x元素每個(gè)重復(fù)次數(shù),times:each后的向量的處理,如果times是單個(gè)值,則each后的值整體重復(fù)times次數(shù),如果是x each后的向量相等長度的向量,則對each后的每個(gè)元素重復(fù)times同一位置的元素的次數(shù),否則會(huì)報(bào)錯(cuò);length.out指times處理后的向量最終輸出的長度,如果長于生成的向量,則補(bǔ)齊。也就是說rep會(huì)先處理each參數(shù),生成一個(gè)向量X1,然后times再對X1進(jìn)行處理生成X2,length.out在對X2進(jìn)行處理生成最終輸出的向量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)) ?#非等長模式,出現(xiàn)錯(cuò)誤
Error in rep(1:4, times = c(1, 2, 3)) : invalid 'times' argument
> rep(1:4,each=2,times=c(1,2,3,4)) #還是非等長模式,因?yàn)閑ach后的向量有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) #重復(fù)的例子啊,莫拍我
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的使用,循環(huán)補(bǔ)齊注意下
[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函數(shù)完畢!
轉(zhuǎn)載于:https://www.cnblogs.com/business-analysis/p/3414997.html
總結(jié)
以上是生活随笔為你收集整理的R中rep函数的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WPF案例:如何设计历史记录查看UI
- 下一篇: 主成分分析(PCA)算法,K-L变换 角