2014-02-13 29 views
2

我很困惑,如何在R.中生成一系列(如1,2,2,3,3,3,4,4,4,4) 我使用for looprep功能這樣,如何生成一個系列(1,2,2,3,3,3,4,4,4,4)

for (i in 1:10) 
{rep(i,i)} 

,但我不能把它們粘貼在一起。

+0

@Julius THX!關於1,-2,-2,3,3,3,-4,-4,-4,-4,5,5,5,5,5? – coco

+0

我已經更新了我的答案。 – Julius

+0

謝謝你。它非常簡單,只需應用乘法。我想我必須更加努力地學習。 – coco

回答

6
rep(1:4, 1:4) 
[1] 1 2 2 3 3 3 4 4 4 4 

同樣,對於另一系列中,我們得到

rep(1:5, 1:5) * (-1)^rep(0:4, 1:5) 
[1] 1 -2 -2 3 3 3 -4 -4 -4 -4 5 5 5 5 5 
+1

對於額外的信用:-),寫出臭名昭着的序列的代碼'1,11,2 1,1 1 1 2,3 1 1 2,...' –

+1

@CarlWitthoft,很好的一個,'cw <-function (X,N)如果(N> 0){打印(X);○<-rle(strsplit(X, 「」)[[1]]); CW(paste0(鄰$ L,O $ v,塌陷= 「」),n-1)}'並嘗試'cw(「1」,10)' – Julius

+2

酷解決方案!我寫了一段時間使用這個方法:'morrisseq <-function(seqlen){' 'theseq < - list(1)' 'for(j in 2:seqlen){' 'thetab <-table (theseq [[j-1]])' '#如果用'as.vector'取代'unlist'''會更令人滿意'theseq [[j]] < - as.vector(sapply(1:length ),函數(k)''c(thetab [k],as.numeric(names(thetab)[k]))))' '}' 'return(theseq)' '}' –