在* apply中退出一个函数 [英] Exit a function within *apply

查看:136
本文介绍了在* 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 and replicate (etc.) run a specified number of times. Putting sapply(1:N, function(n){expr}) will execute expr N times. Supposing I wanted sapply to stop after m runs. Is this possible without making an error? break doesn't work, and a for or while 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 with array(readBin(...), ...) is the best way I've found to do this, but I'd like it to stop when NA 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆