【问题标题】:Weird Behaviour in R if else StatementR if else 语句中的奇怪行为
【发布时间】:2020-11-27 17:51:46
【问题描述】:

我对 R 编程不熟悉了。当我尝试编写我的第一个 if else 语句时,我遇到了一个我不理解的奇怪行为。

当我运行以下代码时:

x = 4;
y=4;
        if (x==y) {
      print('they are equal');
    } else {
      print('they are not equal');
    }

我没有收到任何错误,并且得到了预期的输出。但是,当我更改以下相同代码的缩进时:

if(x==y){print('they are equal');}
else{print('they are not equal');}  

我收到一条错误消息,提示“错误:“else”中出现意外的“else”。

那么这是否意味着 R 是一种像 Python 一样的缩进敏感语言?

【问题讨论】:

  • 来自文档:Note that it is a common mistake to forget to put braces ({ .. }) around your statements, e.g., after if(..) or for(....). In particular, you should not have a newline between } and else to avoid a syntax error in entering a if ... else construct at the keyboard or via source.

标签: r if-statement


【解决方案1】:

根据我有限的经验,在 R 语法中,else 语句应该从 if 语句结束的同一行开始。否则,它将无法正常工作。并且 RNO 缩进敏感的。例如,

这会起作用

if(x==y){print('they are equal')
  } else
    {print('they are not equal')}  



[1] "they are equal"

即使这样也行

if(x==y){print('they are equal')} else
{print('they are not equal')}  

[1] "they are equal"

这也可以

if(x==y){print('they are equal')} else {print('they are not equal')}  

[1] "they are equal"

但是您编写的代码不起作用,因为else 语句不是从if 语句结束的同一行开始。另一个例子是,

这行不通

if(x==y){print('they are equal')} 
else {
  print('they are not equal')}  

另外,您不需要分号。

【讨论】:

  • 请去掉分号。 R 不是 C,在 R 中,分号表示指令的结束,所以 print('they are not equal'); 实际上是 两个 指令:print('they are not equal'); NULL 打印和 @987654331 @指令。
  • @RuiBarradas:我同意,不需要分号。编辑了我的答案。
猜你喜欢
  • 1970-01-01
  • 2018-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-30
  • 1970-01-01
  • 2020-09-09
  • 1970-01-01
相关资源
最近更新 更多