Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 推送返回到父函数_R_Return_Environment - Fatal编程技术网

R 推送返回到父函数

R 推送返回到父函数,r,return,environment,R,Return,Environment,有没有办法强制父函数返回输出?假设我有一个“做某事”的函数,在每个函数的开头,我想“检查某事”。如果检查失败,我想返回“其他内容” 在我下面的例子中,“做某事”是对数,“检查某事”意味着检查变量是否为非负,“其他某事”是否为负无穷大 weird_log <- function(x) { check(x) log(x) } check <- function(x) { if (x <= 0) eval.parent(parse(text = 'return(

有没有办法强制父函数返回输出?假设我有一个“做某事”的函数,在每个函数的开头,我想“检查某事”。如果检查失败,我想返回“其他内容”

在我下面的例子中,“做某事”是对数,“检查某事”意味着检查变量是否为非负,“其他某事”是否为负无穷大

weird_log <- function(x) {
  check(x)
  log(x)
}

check <- function(x) {
  if (x <= 0)
    eval.parent(parse(text = 'return(-Inf)'))
}
一种解决方案是,如果检查发现问题,则从check函数返回'something other',否则返回
NULL
。然后我可以在父函数中编写一个
if
,它就完成了

weird_log <- function(x) {
  y <- check(x)
  if (!is.null(y)) return(y)
  log(x)
}

check <- function(x) {
  if (x <= 0) {
    -Inf
  } else {
    NULL
  }
}
:


奇怪的日志因为答案实际上并没有回答这里的问题,那就是如何做你问的事情

returnFromParent <- function() {
  call <- rlang::expr(return()) 
  rlang::eval_bare(call, env = parent.frame())
}

foo <- function(){
  returnFromParent()
  print("you should not see this")
}

foo()

returnFromParent我没有指定这一点,但是检查的输出可能会根据内部的几个条件而有所不同。因此,检查不能简单地返回
TRUE
/
FALSE
。我也不能使用
stop()
,这个问题不能接受错误。这不会改变我的观点。Return语句应该始终是要从中返回的函数的一部分。例如,check可以返回一个整数值,您可以在父函数中使用switch。这并不是问题的答案。这些关于wee徽章的答案实际上激怒了社区,对社区有害。如果你认为我关心一些互联网点,那你就大错特错了。我关心的是不要推广不好的做法。为什么你甚至需要
parse(text='return(-Inf))
eval.parent(return(-Inf))
不会做同样的事情吗?我不知道你们是从哪里学来的,但这是一种非常糟糕的代码实践。好的方面,我已经把它复杂化了。
weird_log <- function(input) {
  y <- check(input)
  if (!is.null(y)) return(y)
  list(log = log(input$x))
}

check <- function(input) {
  if (is.null(input$x)) {
    list(error = 'x is missing')
  } else if (!is.numeric(input$x)) {
    list(error = 'x is not numeric')
  } else if (x <= 0) {
    list(log = -Inf, warn = 'x is not positive')
  } else {
    NULL
  }
}
weird_log <- function(x) {
  if (check(x)) return(-Inf)
  log(x)
}

check <- function(x) {
  x <= 0
}

weird_log(10)  # 2.302585
weird_log(-10) # -Inf
weird_log <- function(x) {
  check(x)
  log(x)
}

check <- function(x) {
  if(x <= 0) stop("x <= 0", call. = FALSE)
}

weird_log(10)  # 2.302585
weird_log(-10) # Error: x <= 0
returnFromParent <- function() {
  call <- rlang::expr(return()) 
  rlang::eval_bare(call, env = parent.frame())
}

foo <- function(){
  returnFromParent()
  print("you should not see this")
}

foo()