R 返回包含()块的函数

R 返回包含()块的函数,r,R,return()在with()块中如何工作? 下面是一个测试函数 test_func 10){ 消息('第1步内') 报税表(1) } ) 消息(“步骤1之后”) 如果(y>10){ 消息('在第2步中') 返回(2) } 消息(“步骤2之后”) } 函数在返回(1)后继续运行 df我认为这里的要点是return()设计用于使用特定值将当前范围退出到父范围。在跑步的情况下 return("hello") # Error: no function to return from, jump

return()
with()
块中如何工作? 下面是一个测试函数

test_func 10){
消息('第1步内')
报税表(1)
}
)
消息(“步骤1之后”)
如果(y>10){
消息('在第2步中')
返回(2)
}  
消息(“步骤2之后”)
}
  • 函数在返回(1)后继续运行

df我认为这里的要点是
return()
设计用于使用特定值将当前范围退出到父范围。在跑步的情况下

return("hello")
# Error: no function to return from, jumping to top level
您会收到一个错误,因为我们正在从全局环境调用它,并且没有您要跳回的父作用域。注意,由于R的惰性计算,传递给函数的参数通常在传递它们的环境中进行计算。所以在这个例子中

f <- function(x) x
f(return("hello"))
# Error in f(return("hello")) : 
#   no function to return from, jumping to top level
这个
eval()
创建了一个新级别的作用域,我们可以从中逃出,因为我们没有直接计算传递给函数的参数,我们只是在不同的环境中运行这些命令,因此在全局环境中不再计算
返回值,因此没有错误。因此,我们创建的函数基本上与调用

with(NULL, return("hello"))
# [1] "hello"
这与类似

print(return("hello"))
# no function to return from, jumping to top level
其中直接计算参数。因此,在这种情况下,
return()
的不同含义实际上是非标准评估的副作用

return()
with()
中使用时,您不是从调用
with()
的函数返回,而是从为您运行命令而创建的
with()
作用域返回


@IceCreamToucan留下的评论已经提到了如何解决这个特殊问题。您只需将返回移动到
with()

的外部,可能会遗漏问题的实质,但解决方法是将
移动到
if
的内部:
if(with(df,x>10))
。如果返回值需要
with
,您也可以将
with
放入
return
中,例如
return(with(df,1))
。谢谢@IcecreamToucanInterest<代码>与(iris,返回(1))
不会导致错误,即使函数中未使用
return
。类似地,对于
local(返回(1))
f <- function(x) eval(substitute(x))
f(return("hello"))
# [1] "hello"
with(NULL, return("hello"))
# [1] "hello"
print(return("hello"))
# no function to return from, jumping to top level