我有一个带范围的问题函数,我需要执行一个while循环来给定范围。以下是我编写的伪代码。在这里,我打算从排序列表中读取文件,并且start = 4和end = 8表示读取文件4至8。
readFiles<-function(start,end){
i = start
while(i<end){
#do something
i += 1
}
}
我需要知道如何在R中执行此操作。感谢您的帮助。
您可以尝试以下方法:
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
在这里,readFiles2
是if ... for
解决方案,readFiles
也是while
解决方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句