2015-11-02 100 views
0

我有一個問題函數,它需要一個範圍,我需要爲給定範圍執行一個while循環。下面是我寫的僞代碼。在這裏,我想從一個排序列表讀取文件,並開始= 4和結束= 8就意味着讀取文件4〜8如何執行一個循環來改變迭代次數R

readFiles<-function(start,end){ 
    i = start 
    while(i<end){ 
     #do something 
     i += 1 
    } 
} 

我需要知道如何做到這一點的R.任何幫助表示讚賞。

+1

會'lapply(mylist [start:end],function(x){do something}'是另一種方法嗎? – Heroka

+1

如果你用'i <-start'替換'i = start','i mra68

+0

非常感謝@ mra68的答案。它工作正常! – SriniShine

回答

3

你可以試試這個:

readFiles<-function(start,end){ 
    for (i in start:end){ 
     print(i) # this is an example, here you put the code to read the file 
# it just allows you to see that the index starts at 4 and ends at 8 
    } 
} 

readFiles(4,8) 
[1] 4 
[1] 5 
[1] 6 
[1] 7 
[1] 8 

正如指出的mra68,如果你不希望這樣的功能做一些事情,如果end>start你能做到這一點的更多信息:

readFiles<-function(start,end){ 
    if (start<=end){ 
     for (i in start:end){ 
      print(i) 
     } 
    } 
} 

它不會爲readFiles(8,4)做任何事情。使用print(i)作爲循環的功能,它比while如果start<=end稍快也快,如果end>start

Unit: microseconds 
       expr  min  lq  mean median  uq  max neval cld 
    readFiles(1, 10) 591.437 603.1610 668.4673 610.6850 642.007 1460.044 100 a 
readFiles2(1, 10) 548.041 559.2405 640.9673 574.6385 631.333 2278.605 100 a 

Unit: microseconds 
       expr min lq mean median uq max neval cld 
    readFiles(10, 1) 1.75 1.751 2.47508 2.10 2.101 23.098 100 b 
readFiles2(10, 1) 1.40 1.401 1.72613 1.75 1.751 6.300 100 a 

這裏,readFiles2if ... for解決方案,readFileswhile解決方案。

+0

這不是100%相當於問題中的C語法,考慮'end mra68

+0

非常感謝@etienne的回答。它工作的很好! – SriniShine