if/else 构造函数内部和外部 [英] if/else constructs inside and outside functions
问题描述
当我查看 R 函数时,我经常发现以下结构:
When I look at R functions I often find the following structure:
f <- function(exp=T) {
if (exp)
a <- 1
else
a <- 2
}
f()
f(F)
这将运行而不会出错.但是执行内部函数代码会引发错误,因为 R 可能假定语句在第一次赋值 a <- 1
之后完成,并且无法处理以下其他内容.
This will run without error. But executing the inner function code throws an error as R probably assumes that the statement is finished after the first assignment a <- 1
and cannot handle the following else.
exp=T
if (exp)
a <- 1
else
a <- 2
现在,这对我来说很有意义,但我仍然想了解为什么在函数内部或外部执行时执行的代码的行为不同.
Now, this makes sense to me, but I still would like to understand why the behaviour of the executed code differs when executed inside or outside a function.
推荐答案
这是使用交互式 shell 的结果 (REPL) 运行脚本:
It’s a consequence of using an interactive shell (REPL) to run scripts:
在第一个分支之后,shell 会看到一个完整的语句,因此它假定您已完成输入.不幸的是,R 使用相同的 shell 来解释脚本,即使它们不是交互式输入的——所以即使你将 if
语句保存到一个文件中并且 source
它(或管道它进入 R) 你会在 else
分支上得到错误.
After the first branch the shell has seen a complete statement so it assumes that you’re done typing. Unfortunately, R uses the same shell for interpreting scripts even if they are not typed in interactively – so even when you save the if
statement to a file and source
it (or pipe it into R) you will get the error on the else
branch.
但以下方法可以正常工作:
But the following will work just fine:
if (exp) a <- 1 else a <- 2
在这里,解释器吞下一行并执行它.
Here, the interpreter swallows the line and executes it.
在你的函数中,人们会假设同样适用 - 它确实适用!但是,在你的例子中,函数本身以一个开放的大括号开头,所以 R 必须读取直到找到匹配的右大括号.相比之下,以这个函数声明为例:
In your function one would assume that the same applies – and it does! However, the function itself starts with an open brace in your case, so R has to read until it finds the matching closing brace. By contrast, take this function declaration:
f <- function (exp)
if (exp)
a <- 1
else
a <- 2
在 R 中,您可以定义函数体而无需在函数体周围使用大括号.但是上面的代码会失败,原因与没有大括号的独立 if
失败的原因相同.相比之下,如果我将 if
写在一行上,这段代码将再次起作用.
In R you can define functions without braces around the body. But the above code will fail for the same reason that the standalone if
without braces fails. By contrast, if I had written the if
on a single line this code would once again work.
顺便说一下,您的函数对未使用的变量进行了赋值.您可以(应该)执行以下操作:
Incidentally, your function uses an assignment to a variable that isn’t used. You can (should) do the following instead:
f <- function (exp) {
if (exp)
1
else
2
}
... 和在 shell 中使用 if
时一样:
… and the same when using if
inside the shell:
a <- if (exp) 1 else 2
因为在 R 中,if
是一个表达式,它返回一个值.
because in R, if
is an expression which returns a value.
这篇关于if/else 构造函数内部和外部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!