if/else构造内部和外部函数 [英] if/else constructs inside and outside functions

查看:106
本文介绍了if/else构造内部和外部函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我看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.

推荐答案

这是使用交互式外壳程序的结果( 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
}

………与在外壳中使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆