gpt4 book ai didi

function - 在 R 中,用于跳出函数而不执行其余部分的关键字是什么?

转载 作者:行者123 更新时间:2023-12-02 21:41:37 27 4
gpt4 key购买 nike

我想知道 R 中是否有任何关键字可以跳出函数而不执行其余部分。在 C、Java 或 Matlab 中,有关键字“return”。但 R 中的“return”关键字的工作方式与这些语言中不同。这是一个例子,

myfunc = function() {
if (TRUE) {
return # hopefully, jump out of the function
}
print('the rest of the function is still executed!')
}

在示例中,像 Java 这样的语言在满足“return”时不会执行“其余部分”,而在 R 中,“return”仅在 if 语句的范围内,其余函数仍然执行。在这个特定的示例中,我可以添加一个“else” block 来实现它,但我想知道是否有任何关键字可以提供与 Java 等类似的行为。谢谢。

最佳答案

您显示的实际上是语法上有效的 R 代码...但是您犯了未向返回提供值的错误。所以这是一个更正的版本:

R> myfunc <- function() {
if (TRUE) {
return(NULL) # hopefully, jump out of the function
}
print('the rest of the function is still executed!')
}
myfunc <- function() {
+ if (TRUE) {
+ return(NULL) # hopefully, jump out of the function
+ }
+ print('the rest of the function is still executed!')
+ }
R> myfunc()
NULL
R>

关于function - 在 R 中,用于跳出函数而不执行其余部分的关键字是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6284432/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com