实验目的

熟悉并掌握R语言中条件判断语句的编写

实验原理

R的条件判断语句和C语言很相似,具体语法为:if(condition) 语句1 else 语句2,其中condition为逻辑运算,当condition成立时,其值为真,执行”语句1“,不成立则执行语句2

实验步骤

编写简单的条件判断语句

> x <- 1
> if(x==1){print("x is true")}else{print("x is false")}
[1] "x is true"

另一个例子:

> x <- c("what","is","truth")
> if("Truth" %in% x) {
+     print("Truth is found")
+ } else {
+     print("Truth is not found")
+ }
[1] "Truth is not found"

一个if语句可以跟随一个可选的else if...else语句,这对使用单个if...else else语句来测试各种条件非常有用:

> 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"

if语句可以放在函数定义中:

> ifpositive <- function(x) {
+     if(x>0) print("The number is positive")
+     else if(x==0) print("The number is zero")
+     else print("The number is negative")
+ }
> ifpositive(-7)
[1] "The number is negative"

results matching ""

    No results matching ""