提前终止基于应用的功能(类似于休息?)

use*_*319 10 r

我正在寻找一种在某些条件下提前终止应用函数的方法.使用for循环,类似于:

FDP_HCFA = function(FaultMatrix, TestCosts, GenerateNeighbors, RandomSeed) {    
  set.seed(RandomSeed)

  ## number of tests, mind the summary column
  nT = ncol(FaultMatrix) - 1
  StartingSequence = sample(1:nT)
  BestAPFD = APFD_C(StartingSequence, FaultMatrix, TestCosts)
  BestPrioritization = StartingSequence
  MakingProgress = TRUE
  NumberOfIterations = 0
  while(MakingProgress) {
    BestPrioritizationBefore = BestPrioritization
    AllCurrentNeighbors = GenerateNeighbors(BestPrioritization)

    for(CurrentNeighbor in AllCurrentNeighbors) {
      CurrentAPFD = APFD_C(CurrentNeighbor, FaultMatrix, TestCosts)

      if(CurrentAPFD > BestAPFD) {
        BestAPFD = CurrentAPFD
        BestPrioritization = CurrentNeighbor            
        break
      }
    }

    if(length(union(list(BestPrioritizationBefore),
                    list(BestPrioritization))) == 1)
      MakingProgress = FALSE

    NumberOfIterations = NumberOfIterations + 1
  }
}
Run Code Online (Sandbox Code Playgroud)

我想用一些推导来重写这个函数apply.特别是,终止对第一个人的评估,增加适应性,从而避免考虑其余人群的成本.

Jor*_*eys 17

我估计你并没有真正掌握apply家庭及其目的.与一般的想法相反,它们等于任何for-loop.可以说大多数for-loops相当于a apply,但这是另一回事.

Apply完全如下所示:它按顺序在一些类似的参数上应用函数,并返回结果.因此,根据定义,您无法摆脱申请.您不再在全局环境中运行,因此原则上您不能保留全局计数器,在每次执行后检查一些条件并调整循环.您可以使用assign或访问全局环境甚至更改变量<<-,但这非常危险.

理解上的差异,不读书apply(1:3,afunc)for(i in 1:3) afunc(i),但作为

afunc(1)
afunc(2)
afunc(3)
Run Code Online (Sandbox Code Playgroud)

在一个(块)声明中.这更好地反映了你正在做的事情.为等效breakapply根本没有任何意义,因为它更是一个代码比一个循环块.


J. *_*in. 2

除了让示例代码正常工作之外,*我认为这是一个明显的例子,循环是正确的选择。尽管 R 可以将函数应用于整个变量向量 [编辑:但您必须在应用之前决定它们是什么],在这种情况下,我将使用循环while来避免运行不必要的重复的成本。警告:我知道循环与计时测试for相比具有优势,但我还没有看到类似的测试。查看http://cran.r-project.org/doc/manuals/R-lang.html#Control-structs中的一些选项。applywhile

while ( *statement1* ) *statement2*
Run Code Online (Sandbox Code Playgroud)