I reckon that you don't really grasp the apply
family and its purpose. Contrary to the general idea, they're not the equivalent of any for
-loop. One can say that most for
-loops are the equivalent of an apply
, but that's another matter.
Apply
does exactly as it says: it applies a function on a number of similar arguments sequentially, and returns the result. Hence, by definition you cannot break out of an apply. You're not operating in the global environment any more, so in principle you cannot keep global counters, check after each execution some condition and adapt the loop. You can access the global environment and even change variables using assign
or <<-
, but this is pretty dangerous.
To understand the difference, don't read apply(1:3,afunc)
as for(i in 1:3) afunc(i)
, but as
afunc(1)
afunc(2)
afunc(3)
in one (block) statement. That reflects better what you're doing exactly. An equivalent for break
in an apply
simply doesn't make sense, as it is more a block of code than a loop.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…