在 *apply 内退出函数 [英] Exit a function within *apply

查看:28
本文介绍了在 *apply 内退出函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

sapplyreplicate(等)运行指定的次数.放入 sapply(1:N, function(n){expr}) 将执行 expr N 次.假设我希望 sapply 在 m 运行后停止.这可能不会出错吗?break 不起作用,forwhile 循环在我的上下文中会太慢.

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.

类似于:

sapply(1:N, function(n){
  #some expression
  if(identical(n, m)) break
})

除了中断不起作用.

我想做什么:

创建一个函数来读取已定义结构但未知长度的大型(二进制)数据文件.将 replicatearray(readBin(...), ...) 一起使用是我发现的最佳方法,但我希望它停止当 NA 开始返回时(即到达文件末尾).

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;}}) ) 

虽然还是运行了n次,但至少不会每次都执行操作,节省了资源.而且我无法完全弄清楚为什么简化并没有完全奏效,我不得不使用 unlist.

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天全站免登陆