R Control Structure

switch Statement

A switch statement in R allows 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

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

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.

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.

Read about if statement in R

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

In R Language, the if statement(s) is used for making a decision. The if statement in R is used to run the block of statements when a certain condition is met. 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 an if statement is

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

The code inside the brackets of 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 if statement evaluates to false. The basic syntax of an 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

For example,

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

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 & d < 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.

Read about for loops

For loop in R | Simulating Data in R using For loop

In different programming languages and R, the for loop (for statement) allows one to specify the set of codes (commands) that should be repeated a fixed number of times. For loop in R is not limited to integers or even numbers in the input. The character vectors, logical vectors, lists, or even expressions can also be used in a for loop.

The general syntax of the for loop is

for (named vector) {
   statements (R codes)
}

The curly braces contain a set of commands so that these commands can be treated as a single command and can be repeated the desired number of times. However, if there is only a single statement then there is no need to use curly races.

Let us understand the loop through different examples. Note that some of the examples can be done without the use of a for loop or with alternatives such as apply(), lapply(), sapply(), and tapply() functions.

Example: Suppose you want to compute the squared values for 1 to 10. Let us doe this using a for loop as shown below:

for (i in 1:10){
    squared <-i ^2
    print(squared)
}

Note: if you write print(squared) command outside the for loop (after the curly braces), then the last result of the loop iteration will be displayed in the console only, that is, the square of the last number (n = 10) will be printed.

To store the result of each iteration in a variable (vector, matrix, data frame, or list), a container (variable) needs to be specified of the sample length as that of the loop. For example, the outcome of each iteration (from the above example) can be stored in a variable as,

result <- vector("numeric", 10)
for (i in length(result) ){
    squared <- i^2
    result[i] <- squared
}
result

Now results can be displayed without print() command as the results are stored in a container (vector variable). To store results in a data frame or matrix (in the form of the table) with iteration number, the above example can be extended as

result <- data.frame(matrix(nrow = 10, ncol = 2))
colnames(result) <- c("i", "Square")
for (i in 1:10 ){
    squared <- i^2
    result[i, 1] <- i  # stores iteration number in 1stcolumn of data frame
    result[i, 2] <- squared # stores iteration result in 2nd column of data frame
}
result

Nesting For loop in R

Placing the loop inside the body of another loop is called nesting. For nested loops, the outer loop takes control of the iteration of the inner loop. The inner loop will be executed (iterated) n-times for every iteration of the outer loop. For example

for (i in 1:10){
    for (j in 1:5){
        print(i*j)
    }
}

There will be a total of 50 iterations. For each iteration of the first loop (outer loop), there will be five iterations in the inner loop.

The break statement can be used inside a loop if one wants to stop the iteration when a certain condition (situation) occurs and the control will be out of the loop when the condition is satisfied. For example,

n <- 1:5
for (i in x){
   if( i == 3){
     break
   }
print(i)
}

It is also possible to jump to the next iteration using the next statement when certain conditions are satisfied. For example,

n <- 1:5
for( i in x ){
    if (i==2){
       next
    }
print(i)
}

Now consider the example of for loop using a character vector

v = LETTERS[1:10]
for(i in v){
    print(i)
}

Using For Loop in Simulations

In simulations, use loops to generate or resample (bootstrap) data. For example, let’s create a variable having 1000 observations (n = 1000), where each observation is a function of the previous observation according to the equation $y_t$ is 80%, $y_{t-1} + 20%$. with random noise having a mean of 0 and a standard deviation of 1. The value of$y_1=1$.

y<-rep(1,1000)
for(i in 2:1000){
    y[i]=0.8*y[i-1]+0.2*rnorm(1)
}
y

Consider another example of generating simulated data. Suppose, you want to simulate the mixture data and want to repeat it many times and you also want to store the data for each time.

n=100
res = list()
N=1000
X = matrix(0, nrow=N, ncol=2)
for(i in 1:n){
    U = runif(N, min = 0, max = 1)
    for(j in 1:N){
        if (U[j]<0.8){
          X[j,] <- rnorm(1, 2.5, 3)
        } else{
             X[j,] <- rnorm(1,2,1)
          }
        }
    res[[i]]=X
}
res[[100]]
Simulated Data using for loop in R

Note that each res[[i]] is a separate data set, which can be used for further calculations.

Learn about Conditional Statements in R

Online MCQs Statistics with Answers

Scroll to top
x  Powerful Protection for WordPress, from Shield Security
This Site Is Protected By
Shield Security