2017-04-06 84 views
0

1線作爲我的工作的一部分,我應該寫在R.如何打印輸出的列表與R

替換seq()命令我已成功地使一個工作方式類似的功能:

seq2 <- function(a,r,n){ #a is the starting number, r is the increment, n is the length out 
i <- a 
k <- 1 
repeat{ 
    print(i) 
    i<-i+r 
    k=k+1 
    if(k>n) 
    break 
    } 
} 

但是,輸出結果並不是我想要的。例如,調用seq()命令像這樣的時候:

seq(10,by=5,lenght.out=15) 

輸出

[1] 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 

,而我的代碼有這樣的輸出:

seq2(10,5,15) 
[1] 10 
[1] 15 
[1] 20 
[1] 25 
[1] 30 
[1] 35 
[1] 40 
[1] 45 
[1] 50 
[1] 55 
[1] 60 
[1] 65 
[1] 70 
[1] 75 
[1] 80 

那麼,有沒有辦法調整我的代碼,以便它產生與seq()命令相同的輸出?

感謝

回答

1

您可以創建函數內的一個新的載體,並在年底返回向量:

seq2 <- function(a,r,n){ #a is the starting number, r is the increment, n is the length out 
    i <- a 
    k <- 1 
    out = c() 
    repeat{ 
    out = c(out,i) 
    i<-i+r 
    k=k+1 
    if(k>n) 
     break 
} 
return(out) 
} 
+0

謝謝!完美的作品:D –