if - else if - else 语句和括号 [英] if - else if - else statement and brackets
问题描述
我理解写if - else if"语句的常用方法如下:
I understand the usual way to write an "if - else if" statement is as follow:
if (2==1) {
print("1")
} else if (2==2) {
print("2")
} else {
print("3")
}
或
if (2==1) {print("1")
} else if (2==2) {print("2")
} else print("3")
相反,如果我这样写
if (2==1) {
print("1")
}
else if (2==2) {
print("2")
}
else (print("3"))
或者这样:
if (2==1) print("1")
else if (2==2) print("2")
else print("3")
该语句不起作用.你能解释一下为什么 }
必须在同一行中的 else
或 else if
之前吗?有没有其他方法可以在 R 中编写 if-else if-else 语句,尤其是没有括号?
the statement does NOT work. Can you explain me why }
must precede else
or else if
in the same line? Are there any other way of writing the if-else if-else statement in R, especially without brackets?
推荐答案
R 逐行读取这些命令,因此在执行 if 语句后的表达式后,它认为您已完成.请记住,您可以使用 if
而无需添加 else
.
R reads these commands line by line, so it thinks you're done after executing the expression after the if statement. Remember, you can use if
without adding else
.
你的第三个例子将在一个函数中工作,因为整个函数是在执行之前定义的,所以 R 知道它还没有完成(在 if() do
).
Your third example will work in a function, because the whole function is defined before being executed, so R knows it wasn't done yet (after if() do
).
这篇关于if - else if - else 语句和括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!