如何从lapply循环调用顶层(跳过/传递) [英] How to call top level from lapply loop (skip/pass)

查看:98
本文介绍了如何从lapply循环调用顶层(跳过/传递)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个lapply循环,如果出现某个要求,它将停止...

作为例子:

<$ p $ (1:100,功能(z){

得分< - - 得分+ 1

if(score> = 10){
break
}
})

但是,在lapply循环中, break / pass 没有停止参数。

我知道这个例子听起来很愚蠢。然而,原始代码有太多的依赖关系,很容易理解...
我的原始循环每次从一个对象中移除一个对象的一个​​项目,但是,如果没有别的东西可以从中删除可以停止。
在正常循环中获得至少0.10秒的短尺寸函数



与正常的for循环跳过参数



 >时间<  - 系统。时间({环肽_分数(序列,频谱)})
> time
usaáriosistema decorrido
6.58 0.00 6.58



with laplly with no skip argument



 >时间<  - 系统时间({环肽_score2(序列,频谱)})
> time
usuáriosistema decorrido
6.72 0.00 6.72


解决方案 lapply 发生的代码以及所应用的函数有一些控制:

/ b>

  withRestarts(
lapply(
1:10,
function(x){
$ cat(x)
if(x> 5)invokeRestart(stopLoop)
}),
stopLoop = function()message(Loop Stopped)

产生:

  123456 
循环已停止

基本上, withRestarts / invokeRestart 有点像GOTO语句,允许您跳出循环。



所有这些都说明了,我不会在6.7秒的运行时间内为任何大的代码重构努力提供0.1秒的改进。

另外,if您可以做上面的事情,你可以简单地把你的代码转换成 for 循环,这看起来更合适,因为你希望a)跳出循环,b)使用<< - 操作符引起副作用。


I want to create a lapply loop that if attends a certain requirement, it will stop...
as an example:

score <- 0
lapply(1:100, function(z){

    score <<- score + 1

    if(score >=10){
        break
    }
})

However, there is no stop argument as break/pass in a lapply loop.

I know this example sounds stupid. However, the original code has too many dependencies to be easily understood... My original loop removes an item from a vector an object every time, however, if there is nothing else to be removed from it can stop. I've gain at least 0.10 seconds with this in a normal loop short sized function

with normal "for loop" with skip argument

> time <- system.time({cyclopeptide_score(sequence, spectrum)})
> time
  usuário   sistema decorrido 
     6.58      0.00      6.58 

with laplly with no skip argument

> time <- system.time({cyclopeptide_score2(sequence, spectrum)})
> time
  usuário   sistema decorrido 
     6.72      0.00      6.72 

解决方案

To directly answer your question, here is an option (assuming you have some control of the code where the lapply happens, and of the function being applied):

withRestarts(
  lapply(
    1:10, 
    function(x) {
      cat(x)
      if(x > 5) invokeRestart("stopLoop")
  } ),
  stopLoop=function() message("Loop Stopped")
)

Produces:

123456
Loop Stopped

Basically, withRestarts/invokeRestart acts a little bit like a GOTO statement, which allows you to break out of the loop.

All this said, I wouldn't base any big code refactorings efforts on a 0.1 second improvement on 6.7 seconds run time.

Also, if you can do the above, you can probably just as easily turn your code into a for loop, which seems more appropriate given your desire to a) break out of the loop, b) use the <<- operator to cause side effects.

这篇关于如何从lapply循环调用顶层(跳过/传递)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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