Skip to main content

Mastering Control Structures in R Programming: Learn How to Use If-Else, Switch Case, and For Loops Like a Pro!

The Beginner’s Guide to Control Structures (If-Else, Switch-Case, & For Loops) in R Programming:

Control structures are essential in programming languages as they determine the flow of the program. In R programming, there are several control structures available, including if-else, switch case, and for loops.


If-Else statement:

The if-else statement is used to check the condition and execute a block of code accordingly. The syntax of the if-else statement in R is as follows:

if (condition) { 
                     # Execute code if the condition is true 
                     } 
else { 
        # Execute code if the condition is false 
        }

For example, consider the following code that checks whether a number is even or odd:

num <- 10 
if (num %% 2 == 0) { 
                                 print("The number is even") 
                                 } 
else { 
         print("The number is odd") 
        }

Output:
[1] "The number is even"

Switch case statement:

The switch case statement is used to compare a single value against multiple possible values and execute a block of code accordingly. The syntax of the switch case statement in R is as follows:

switch (expression, 
           value1 = code1, 
           value2 = code2, 
           ..., 
           default = codeN)

For example, consider the following code that checks the day of the week:

day <- "Monday"

switch (day,
        "Monday" = print("Today is Monday"),
        "Tuesday" = print("Today is Tuesday"),
        "Wednesday" = print("Today is Wednesday"),
        "Thursday" = print("Today is Thursday"),
        "Friday" = print("Today is Friday"),
        "Saturday" = print("Today is Saturday"),
        "Sunday" = print("Today is Sunday"),
        print("Invalid day"))

Output:
[1] "Today is Monday"

For loop:

The for loop is used to execute a block of code repeatedly for a specified number of times. The syntax of the for loop in R is as follows:

for (variable in sequence) {
  # Execute code for each value of the variable
}

For example, consider the following code that prints the numbers from 1 to 5:
for (i in 1:5) { 
                    print(i)
                    }

Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5


Practice Material:

Here are a few practice exercises to help you get started:

  • Write a program that takes the temperature as input and prints "It's cold outside" if the temperature is below 10 degrees Celsius, "It's warm outside" if the temperature is between 10 and 25 degrees Celsius, and "It's hot outside" if the temperature is above 25 degrees Celsius.
  • Write a program that takes the day of the week as input and prints "Weekday" if it's Monday to Friday, "Weekend" if it's Saturday or Sunday, and "Invalid day" for any other value.
  • Write a program that calculates the sum of the first 10 natural numbers using a for loop.
  • For more practice you should start swirl's lesson number eight in R Programming. Complete download process of swirl and R Programming is here, click on the link!
  • You can look in to the practice and reading material that is provided in the text book, click here to download the textbook.
  • Lecture slides can be downloaded from here. It would be great if you go through them too.

These practice materials are suitable for you to get hands-on experience with control structures in R programming. Good luck!

Comments

Popular posts from this blog

Mastering Debugging in R: Essential Tools and Techniques

The Beginner’s Guide to Debugging Tools in R: Debugging is an essential part of programming in any language, including R. When your code doesn't work as expected, it can be frustrating and time-consuming to find and fix the issue. Fortunately, R provides a variety of debugging tools that can help you identify and fix issues in your code more efficiently. In this blog post, we'll explore some of the most useful debugging tools in R, along with examples of how to use them. The browser() function:  The browser() function is a built-in debugging tool in R that allows you to pause the execution of your code and inspect the values of variables at that point. To use the browser() function, simply insert it into your code where you want to pause the execution. For example: my_function <- function(x) {                                              y <- x * 2  ...

Mastering Loop Functions in R: Exploring tapply and split for Data Manipulation and Analysis

The Beginner’s Guide to Loop Functions in R: Loop functions are powerful tools in R for data manipulation and analysis . They provide efficient and concise ways to apply a function to multiple elements of a data structure. Two commonly used loop functions in R are tapply and split . In this blogpost, we will explore these functions in detail and learn how they can be used to effectively analyze and manipulate data. We will cover the basics of these functions and provide practical examples to illustrate their usage. tapply()  tapply is a loop function in R that applies a function to subsets of a vector or array based on a grouping factor. The syntax of tapply is as follows: tapply(X, INDEX, FUN) where X is the input vector or array, INDEX is the grouping factor, and FUN is the function to be applied. Now suppose we have a data frame containing information about various cities, including their population and average temperature. We could use tapply() to calculate the mean popula...

Mastering R Data Types: Matrices, Factors, Missing Values, Data Frames, and Names Attribute

The Beginner’s Guide to R Data Types: R is a programming language that is widely used for data analysis and statistical computing. It has a powerful set of data structures, including vectors, lists, and data frames, that allow users to work with data in a flexible and efficient way. Matrices A matrix is a two-dimensional array in R that can contain elements of any data type. You can create a matrix using the matrix() function. For example: # Create a matrix with 3 rows and 2 columns  my_matrix <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 3, ncol = 2) Factors A factor is a type of variable in R that represents categorical data. Factors are stored as integers, where each integer corresponds to a level of the factor. You can create a factor using the factor() function. For example: # Create a factor with three levels: "low", "medium", "high"  my_factor <- factor(c("low", "high", "medium", "high", "low")) Missin...