如果R中的语句只能有一行? [英] if statement in R can only have one line?

查看:218
本文介绍了如果R中的语句只能有一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用if语句尝试一个很小的代码,虽然它非常简单,但我在这里真的很困惑的是代码

I was trying a tiny code with if statement, although it is very simple,but there is something I really confused here is the code

n<-857
while(n!=1){
if(n<=0)
 print("please input a positive integer")
else if(n%%2==0)
 n<-n/2
 print(n)
else
 n<-3*n+1
 print(n)
  }

如上所述,在R中运行此代码时,出现错误,但是如果我更改if语句就像这样

as we see above,when running this code in R, there comes the error,but if I change the if statement like this

if(n<=0)
     print("please input a positive integer")
    else if(n%%2==0)
     n<-n/2
    else
     n<-3*n+1

没关系,我的问题是我们每次判断只能写一行吗?如果我想在每个评判后做更多的事情,我该怎么办,就像这个案例一样,我想改变n的值,但也想要显示它,我该怎么办?非常感谢

it is ok ,my question is that can we only write one line under each judgement? if I want to do something more after each judge, what should I do ,just like this case, I want to change the value of n,but also want to display it, what should I do? thank you very much

推荐答案

确切地说,这不是关于行而是关于语句。您可以在一行中包含整个 if else 语句:

To be precise, this is not about lines but about statements. You can have the whole if else statement in one line:

> if (TRUE) 1 else 3
[1] 1

声明将在行的结尾(如果完成),如果你逐行输入代码,你可以很好地在交互模式中看到:

A statement will end at the end of the line (if complete), you can see that nicely in interactive mode if you enter the code line by line:

> if (TRUE) 
+ 1
[1] 1
> else
Fehler: Unerwartete(s) 'else' in "else" # error: unexpected 'else' in "else"
> 3
[1] 3

if 可以以形式出现if(条件)语句 if(condition)语句else else.statement ,解释器假设第一个版本意味着如果语句在第2行之后完成 - 在交互模式下它无法明智地等待接下来是否出现 else 。这在 source d代码中是不同的 - 在下一行中它是明确的形式。

if can come in form if (condition) statement or if (condition) statement else other.statement, the interpreter assumes the first version is meant if the statement is complete after line 2 - in interactive mode it cannot sensibly wait whether an else appears next. This is different in sourced code - there it is clear with the next line which form it is.

分号结束语句:

> if (TRUE) 1; else 3
[1] 1
Fehler: Unerwartete(s) 'else' in " else"  # error: unexpected 'else' in "else"

但在条件的每个分支中只能有一个语句

But you can only have one statement in each branch of the condition.

> if (TRUE) 1; 2 else 3
[1] 1
Fehler: Unerwartete(s) 'else' in " 2 else" # error: unexpected 'else' in "2 else"

卷曲括号组语句,使它们显示为一个语句。

Curly braces group statements so they appear as one statement.

> if (TRUE) {1; 2} else 3
[1] 2

这篇关于如果R中的语句只能有一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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