R(7), Decision and Loop

Published: by Creative Commons Licence

Decision

R provides three types of decision statements:

  1. if
  2. if…else
  3. switch
if(boolean_expression) {
    // statement(s) will execute if the boolean expression is true.
}

if(boolean_expression) {
   // statement(s) will execute if the boolean expression is true.
} else {
   // statement(s) will execute if the boolean expression is false.
}

switch(expression, case1, case2, case3....)

Example I:

x <- switch(
   3,
   "first",
   "second",
   "third",
   "fourth"
)
print(x)

# [1] "third"

Example II:

switch(1,2*3,sd(1:5),runif(3))  #返回(2*3,sd(1:5),runif(3))list中的第一个成分 
switch(2,2*3,sd(1:5),runif(3))  #返回第二个成分
switch(3,2*3,sd(1:5),runif(3))  #返回第三个成分

# [1] 6
# [1] 1.581139
# [1] 0.31508117 0.04610938 0.19489747

Loop

  1. repeat()
  2. while
  3. for
  4. break
  5. next
repeat { 
   commands 
   if(condition) {
      break
   }
}

while (test_expression) {
   statement
}

for (variable in conditions) {
   statement
}

next in R plays the similar role in loop structure as continue in other languages.


var() this function calculates the variance.

sd(): this function calculates the standard deviation.

runif(n): this function generates n random numbers in the range of 0 to 1, which obey Normal Distribution.