if语句后面可以是一个可选的else语句,当布尔表达式为false时执行。
在R中创建if ... else语句的基本语法是 -
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true.
} else {
// statement(s) will execute if the boolean expression is false.
}
如果布尔表达式的计算结果为真,则将执行if代码块,否则将执行代码块。x <- c("what","is","truth")
if("Truth" %in% x) {
print("Truth is found")
} else {
print("Truth is not found")
}
[1] "Truth is not found"
这里“Truth”和“truth”是两个不同的字符串。if语句后面可以跟一个可选的else if ... else语句,这对于使用single if ... else if语句测试各种条件非常有用。
当使用if,else if,else语句有几点要记住。
在R中创建if ... else if ... else语句的基本语法是 -
if(boolean_expression 1) {
// Executes when the boolean expression 1 is true.
} else if( boolean_expression 2) {
// Executes when the boolean expression 2 is true.
} else if( boolean_expression 3) {
// Executes when the boolean expression 3 is true.
} else {
// executes when none of the above condition is true.
}
x <- c("what","is","truth")
if("Truth" %in% x) {
print("Truth is found the first time")
} else if ("truth" %in% x) {
print("truth is found the second time")
} else {
print("No truth found")
}
当上面的代码被编译和执行时,它产生以下结果 -[1] "truth is found the second time"
联系客服