2015-11-02 96 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