Stopping a stop function using another function in R

I did a test with a nested function returnin R, but to no avail. I came from Mathematica where this code works well. Here is the toy code:

fstop <- function(x){
  if(x>0) return(return("Positive Number"))
}

f <- function(x){
  fstop(x)
  "Negative or Zero Number"
}

If I rate f(1), I get:

[1] "Negative or Zero Number"

When I was expecting simply:

[1] "Positive Number"

Question: is there some non-standard assessment that I can do in fstop, so I can only get the result fstopwithout changing the ffunction?

PS: I know that I can put it ifinside inside f, but in my real case, the structure is not so simple, and this structure will simplify my code.

+4
source share
2 answers

...

.

, . , return , . .:

https://github.com/wch/r-source/blob/trunk/src/main/context.c

, R , . , C, , . do_return_return do_return eval.c R... .

, "".

+7

, Spacedman , , , tryCatch .

RETURN:

RETURN <- function(x) {
  cond <- simpleCondition("")  # dummy message required
  class(cond) <- c("specialReturn", class(cond))
  attr(cond, "value") <- x
  signalCondition(cond)
}

, RETURN:

f <- function(x) {
  fstop(x)
  "Negative or Zero"
}
fstop <- function(x) if(x > 0) RETURN("Positive Number")  # Note `RETURN` not `return`

, ( wsr " " ) :

wsr <- function(x) {
  tryCatch(
    eval(substitute(x), envir=parent.frame()),
    specialReturn=function(e) attr(e, "value")
) }

:

wsr(f(-5))
# [1] "Negative or Zero"
wsr(f(5))
# [1] "Positive Number"

, , with source. - , wsr.

+3

All Articles