在* apply中退出一个函数 [英] Exit a function within *apply
问题描述
sapply
和 replicate
(等等)运行指定的次数。放置 sapply(1:N,function(n){expr})
将执行 expr
N次。假设我希望 sapply
在m运行后停止。这可能没有发生错误? break
不起作用,或
循环会在我的上下文中太慢。
类似于:
sapply(1:N,function(n){
#some表达式
if(identical(n,m))break
})
除了中断不起作用。
我在做什么:
创建一个函数来读取已定义结构的大(二进制)数据文件,但长度未知。使用
replicate
和array(readBin(...),...)
是我找到的最好方法要做到这一点,但我希望当NA
开始返回时(即到达文件结尾)停止。
<$ c $如果(i){if(x> = 4)(i <-FALSE); 2 * x;}} ))
虽然它仍然运行n次,但至少每次都不执行操作,资源。
我不能确切地说明为什么简化不能一直工作,我不得不使用unlist。
sapply
andreplicate
(etc.) run a specified number of times. Puttingsapply(1:N, function(n){expr})
will executeexpr
N times. Supposing I wantedsapply
to stop after m runs. Is this possible without making an error?break
doesn't work, and afor
orwhile
loop would be too slow in my context.Something akin to:
sapply(1:N, function(n){ #some expression if(identical(n, m)) break })
except that break doesn't work.
What I'm trying to do:
Creating a function to read in large (binary) data files of a defined structure but unknown lengths. Using
replicate
witharray(readBin(...), ...)
is the best way I've found to do this, but I'd like it to stop whenNA
starts to be returned (i.e. end of file is reached).解决方案A partial workaround can be to used in form of global control variable
i<-TRUE unlist( sapply(1:10, function(x){if(i){ if(x>=4)(i<<-FALSE); 2*x;}}) )
Though it still runs n times, at least it does not perform the operation every time and spares resources. And I can't exactly make out why simplification did not work all the way and I had to use unlist.
这篇关于在* apply中退出一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文