Control Structures in R

The post is about different control structures in R Language. In R there are different control structures to control the flow or execution of the program. The control function usually makes use of if statements or their different flavors to control the code based on condition(s). On the other hand, one can repeat some desired task in sequence or based on conditions such as repeated sampling or simulation can be performed using loops such as for loop.

Control Structures in R Language

What is a Control Structure in R?

R language has some standard control structures. Many R expressions/ statements (or code blocks) can be enclosed within braces { }. Control structures define the flow of the program. However, it is more efficient to use built-in functions rather than control structures whenever possible. These allow us to control the flow of execution of a script typically inside of a function.

How many Control Statements are in R Language?

There are eight control statements in R language.

Name all of the Control Statements in R

The names of the control statements in R language are:

  • if
  • if-else
  • for
  • nested loops
  • while
  • repeat and break
  • next
  • return

In general, one can say that there are two types of control structures.

  • Conditional statements (if, if-else, elif, and switch statement)
  • Loops (for loop, while loop, and repeat)

What is “if” control statement in R Language?

The if statements are used when a certain condition is TRUE to perform a specific task. The syntax of an if statement is

if (test expression or condition){
  statement(s)
}

How if statements work, consider the following a simple example

x <- 1:20
if (sample(x, 1) <= 10){
  print("Sampled x is less than 10")
}

From the above example, if the randomly sampled value is less than 10, then the output of the code will be “Sampled x is less than 10”, otherwise nothing will be displayed on the screen as no else is utilized here.

What is a loop in R Language?

A loop is a way to repeat a sequence of instructions/commands under certain conditions. The loops allow us to automate parts of our code that require repetition.

What does mean by the term “Dreaded for Loop”?

In R language, many questions arose about how to accomplish different tasks without the use of a for loop. This is a situation of “Dreaded for Loop”. It is usually desired as programmers try to avoid loops at all costs to speed up their code.

Give an Example of “Dreaded for Loop”

The simplest example of “Dreaded for loop” is the use of vectorization. The vectorization in R speeds up some computation, compared to the use of loops. For example, if x and y are vectors of equal lengths, one can add/sum them as

# Vectorization
x <- 1:5
y <- 5:1
z <- x + y
print(z)


# Using for loop
for (i in length(x)){
 z[i] <- x[i] + y[i]
}
print(z)
Control Structures in R Language

The addition of element-wise values of the $x$ and $y$ vectors is much faster than adding/summing using loops. Note that the use of vectorization also helps the programmers to write shorter, simpler, safer, and faster code.

What is the Purpose of Using the next statement in R?

One can use the next statement if, in a loop, the programmer/ developer wants to skip the current iteration without terminating it loop.

Statistics and Data Analysis

switch Statement in R

In R language, the switch statements allow a variable to be tested for equality against a list of values. Each value in a list is called a case, and the variable being switched on is checked for each case. R switch is almost the same as the if statement regarding working functionality.

The basic syntax is

Basic Syntax of Switch Statement in R Language

switch(expression,
     case 1,
     case 2,
     case 3,
     .
     .
)

The expression values are tested against multiple cases (case1, case2, …, casen). The one-line syntax is,

switch statement in r

An R Language Switch statement allows a default statement can also be added. The default statement will be executed when the Expression value is not matching with any of the case statements.

The following example is a simple command-line type calculator using R.

Simple Calculator Example

number1  <- 30
number2  <- 20
operator <- readline(prompt = "Enter any ARITHMETIC OPERATOR (+, -, *, ^, /, %/%, %%)!: ")

switch(operator,
       "+" = print(paste("Addition (number1+number2) = ", number1 + number2)),
       "-" = print(paste("Subtraction (number1-number2) = ", number1 - number2)),
       "*" = print(paste("Multiplication (number1*number2) = ", number1 * number2)),
       "^" = print(paste("Exponent (number1^number2) = ", number1 ^ number2)),
       "/" = print(paste("Division (number1/number2) = ", number1 / number2)),
       "%/%" = print(paste("Integer Division (number1 %/% number2) = ", number1 %/% number2)),
       "%%" = print(paste("Division (number1 %% number2) = ", number1 %% number2))
)

From the above example, one can easily compute some basic computations on two numbers. The operation on these two numbers depends on the input given to readline( ) the function and the expression in the switch. The operator value from readline() is matched with the options (cases) in the switch statement and results are displayed when matched.

Probability under the F-Curve

Consider another example, for different probabilities, the area under the curve for an F-curve can be selected using the switch as given below.

# q contains the probability under the curve for a F-curve
q <- c(0.25, 0.5, 0.75, 0.999)
test = 3
v1 = 10
v2 = 20

switch(test,
      "1" = print (qf(q[1], df1=v1, df2=v2, lower.tail = T) ),
      "2" = print (qf(q[2], df1=v1, df2=v2, lower.tail = T) ),
      "3" = print (qf(q[3], df1=v1, df2=v2, lower.tail = T) ),
      "4" = print (qf(q[4], df1=v1, df2=v2, lower.tail = T) )
)

The code above will produce F-table values for different probability values.

MCQs in Statistics

MCQs General Knowledge

if Statement in R: if-else, if-else-if Conditional Statement

General Introduction to if Statement in R

In R Language, the if statement(s) is a conditional control used for making a decision. The if statement in R is used to run the block of statements when a certain condition is met. Therefore, if statements are also called conditional statements.

if Statement in R

An if statement consists of a boolean expression followed by one or more statements. The basic syntax for creating a if statement is

if ( boolean expression ) {
      # statements 
      # these statements will execute only if the boolean expression is true
}

The code inside the brackets of the if statement will be executed if the boolean expression in parenthesis evaluates to be true. For example,

x <- 3.0L
if ( is.integer(x) ){
   print("x is an integer")
}

if-else Statement

An if statement can be followed by an optional else statement. The else statement executes only when the boolean expression in the parenthesis of the if statement evaluates to false. The basic syntax of a if-else statement is

if (boolean expression){
        # statement(s) will execute if the boolean expression is true 
}
else{
      # statemenet(s) will execute if boolean expression is false
}
if statement in R syntax

For example,

x <- 31
if ( x %% 2 == 0 ){
   print("X is even")
}else{
  print("X is odd")
}
if Statement in R

if-else-if Statement

An if statement can be followed by an optional else-if-else statement, which is very useful for testing various conditions using a single if-else-if statement. The basic syntax for creating an if-else-if is

if ( boolean expression-1 ){
      # statements execute when the boolean expression-1 is true
} else if ( boolean expression-2 ) {
     # statements execute when the boolean expression-2 is true
} else if ( boolean expression-3 ){
    # statements execute when the boolean expression-3 is true
} else {
    # statements execute when none of the above condition is true
}

For example,

# Consider durbin watson statistics
d = -2
if (d == 2){
   print("no autocorrelation")
} else if (d > 0 &amp; d &lt; 2){
   print("Positive autocorrelation")
} else if (d > 2){
   print("successive error terms are negatively correlated")
} else {
  print("d is less than 0")
}

The value of $d (d=-2)$ will be compared with the expression’s result in the parenthesis of if or else if statement. From all of the if or else if statements only one statement will be true. In the example, $d=-2$ does not match with any of the if (or else if statement), therefore, the last statement (that is else statement) will be executed.

for loops

Computer MCQs Online Test

SPSS Data Analysis

https://rfaqs.com R Frequently Asked Questions