很明显,R的文档反对在"}"one_answers";else"。然而,奇怪的是,第一段代码工作,而第二段代码不工作(语法错误)
第一个程序
x = 1
stupid_function = function(x){
if(x != 1){
print("haha")
}
else if( x == 1){
print("hihi")
}
}
stupid_function(x)
[1] "hihi"
第二个程序
x = 1
if(x != 1){
print("haha")
}
else if( x == 1){
print("hihi")
}
Error in source("~/.active-rstudio-document", echo = TRUE) :
~/.active-rstudio-document:6:3: unexpected 'else'
5: }
6: else
在第二个程序中,它每次看到一行,因此在键入带有}的行时,它不知道还会有带有else的行,因此它假设语句已经结束。
在第一种情况下,它可以在运行之前看到所有的代码,因为它可以看到函数中的所有代码,所以它知道}还没有完成语句。
这行参数适用于if/else,但一般不适用。例如,这将在函数为时产生错误定义。
f <- function(x) {
x
* 2
}
注意,if else
不需要在函数中才能工作。它只需要以连续的形式或以一种方式表示为连续的代码块。一种是在函数中。另一种是将其写在一行中,甚至确保if
块和else
块之间没有换行:
x <- 1
if(x != 1) print('haha') else print('hihi')
[1] "hihi"
更多语句块:
x <- 1
if(x != 1){
print("haha")
} else if( x == 1){ # Note how else begins immediatley after }
print("hihi")
}
[1] "hihi"
请注意,您需要知道何时将换行符放在函数内或函数外。否则,代码可能会失败,甚至给出错误的结果。
使用减法:
x <- 1
x -
2
[1] -1
x <- 1
x
- 2
[1] -2
你需要知道什么时候/在哪里换行。在前面if语句的右括号}
后面加上else总是安全的。即:
if(...){
....
} else if(...){
....
} else {
...
}