Hamburger Icon
  • Labs icon Lab
  • Data
Labs

Programming with R Hands-on Practice

In this lab, you'll start with the basics of R programming by learning how to create variables and understand different data types. Next, you'll delve into more complex data structures like matrices, arrays, and lists, learning how to manipulate multi-dimensional data. By the end, you'll master control statements in R, enabling you to direct the flow of execution in your programs through conditional logic and loops, solidifying your foundational R programming skills.

Labs

Path Info

Level
Clock icon Beginner
Duration
Clock icon 1h 13m
Published
Clock icon Feb 27, 2024

Contact sales

By filling out this form and clicking submit, you acknowledge ourΒ privacy policy.

Table of Contents

  1. Challenge

    Getting Started with R: Variables and Data Types

    RStudio Guide

    To get started, click on the 'workspace' folder in the bottom right pane of RStudio. Click on the file entitled "Step 1...". You may want to drag the console pane to be smaller so that you have more room to work. You'll complete each task for Step 1 in that R Markdown file. Remember, you must run the cells with the play button at the top right of each cell for a task before moving onto the next task in the R Markdown file. Continue until you have completed all tasks in this step. Then when you are ready to move onto the next step, you'll come back and click on the file for the next step until you have completed all tasks in all steps of the lab.


    Getting Started with R: Variables and Data Types

    To review the concepts covered in this step, please refer to the Getting Started with R module of the Programming with R course.

    Understanding variables and data types is important because they are the basic building blocks of any programming language. In R, we have several data types including numeric, character, logical, and raw. This step will help you practice creating variables and assigning different data types to them.

    Let's dive into the world of R programming by practicing the creation of variables and assigning different data types to them. The goal here is to familiarize yourself with the syntax of R and understand how different data types work. You will use the assignment operator (<-) to create variables and assign values to them. You will also practice checking the data type of a variable using the class() function.


    Task 1.1: Creating a Numeric Variable

    Create a numeric variable named num_var and assign the value 10 to it.

    πŸ” Hint

    Use the assignment operator <- to assign the value 10 to the variable num_var.

    πŸ”‘ Solution
    num_var <- 10
    

    Task 1.2: Creating a Character Variable

    Create a character variable named char_var and assign the string 'Hello, R!' to it.

    πŸ” Hint

    Use the assignment operator <- to assign the string 'Hello, R!' to the variable char_var.

    πŸ”‘ Solution
    char_var <- 'Hello, R!'
    

    Task 1.3: Creating a Logical Variable

    Create a logical variable named log_var and assign the boolean value TRUE to it.

    πŸ” Hint

    Use the assignment operator <- to assign the boolean value TRUE to the variable log_var.

    πŸ”‘ Solution
    log_var <- TRUE
    

    Task 1.4: Checking the Data Type of a Variable

    Check the data type of the variable num_var using the class() function.

    πŸ” Hint

    Pass the variable num_var as an argument to the class() function.

    πŸ”‘ Solution
    class(num_var)
    
  2. Challenge

    Exploring Vectors and Factors

    Exploring Vectors and Factors

    To review the concepts covered in this step, please refer to the Exploring Vectors and Factors module of the Programming with R course.

    Working with vectors and factors is important because they are fundamental data structures in R used to store and manipulate data. This step will help you practice creating and manipulating vectors and factors.

    Let's explore the power of vectors and factors in R. The goal here is to understand how to create vectors, assign values to them, and perform operations on them. You will use the c() function to create vectors and the factor() function to create factors. You will also practice ordering and sorting vectors, and performing set operations on them.


    Task 2.1: Creating a Vector

    Create a vector named my_vector with the numbers 1 through 10 using the c() function.

    πŸ” Hint

    Use the c() function to concatenate the numbers 1 through 10 into a vector. The syntax is c(1, 2, 3, ..., 10).

    πŸ”‘ Solution
    my_vector <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    
    # optionally, use `:` to select consecutive numbers
    my_vector <- 1:10
    

    Task 2.2: Assigning Values to a Vector

    Assign the value 100 to the 5th element of my_vector.

    πŸ” Hint

    You can assign a value to a specific element of a vector using the syntax vector[index] <- value

    In this case, the index of the 5th element is 5 and the value to assign is 100.

    Note: If you have used another programming language, you might be accustomed to the first index position being 0 (a 'zero indexed' language). In R, the first index position is 1, not 0.

    πŸ”‘ Solution
    my_vector[5] <- 100
    

    Task 2.3: Performing Operations on a Vector

    Multiply each element of my_vector by 2 and assign the result back to my_vector.

    πŸ” Hint

    You can perform operations on each element of a vector using the syntax vector <- vector * value. In this case, the value is 2.

    πŸ”‘ Solution
    my_vector <- my_vector * 2
    

    Task 2.4: Creating a Factor

    Create a factor named my_factor with the values 'high', 'low', 'medium', 'low', 'high' using the factor() function. Make sure the factor levels are in the right order.

    πŸ” Hint

    The first argument to factor should be a vector of the values. Use the syntax c('value1', 'value2', ...) .

    By default, the order of factor levels will be alphabetical β€” to supply an explicit level order, pass a second argument called levels and supply the ordered levels. Use the syntax:

    factor(c('value1', 'value2', ...), levels = c('level1', 'level2', ...))
    
    πŸ”‘ Solution
    my_factor <- factor(c('high', 'low', 'medium', 'low', 'high'), levels = c('low', 'medium', 'high'))
    

    Task 2.5: Ordering a Vector

    Order my_vector in ascending order and assign the result to a new vector named ordered_vector.

    πŸ” Hint

    You can order a vector in ascending order using the sort() function. The syntax is sort(vector).

    To preserve the new order, make sure to assign the output of sort() to a new variable named ordered_vector.

    πŸ”‘ Solution
    ordered_vector <- sort(my_vector)
    

    Task 2.6: Performing Set Operations on Vectors

    Create a new vector named another_vector with the numbers 5 through 15. Then, find the intersection of my_vector and another_vector and assign the result to a new vector named intersection_vector.

    πŸ” Hint

    You can find the intersection of two vectors using the intersect() function. The syntax is intersect(vector1, vector2).

    You can use a colon : to select a consecutive sequence of numbers. In this case, use 5:15.

    πŸ”‘ Solution
    another_vector <- 5:15
    intersection_vector <- intersect(my_vector, another_vector)
    
  3. Challenge

    Using Matrices, Arrays, and Lists

    Using Matrices, Arrays, and Lists

    To review the concepts covered in this step, please refer to the Using Matrices, Arrays, and Lists module of the Programming with R course.

    Understanding matrices, arrays, and lists is important because they are more complex data structures in R that allow you to store and manipulate multi-dimensional data. This step will help you practice creating and manipulating matrices, arrays, and lists.

    Let's take a step further into the world of R programming by practicing the creation and manipulation of matrices, arrays, and lists. The goal here is to understand how these data structures work and how they can be used to store and manipulate multi-dimensional data. You will use the matrix(), array(), and list() functions to create these data structures, and practice selecting elements from them and performing operations on them.


    Task 3.1: Creating a Matrix

    Create a matrix with 3 rows and 3 columns using the matrix() function. Fill the matrix with numbers from 1 to 9. Assign the matrix to a variable named m.

    πŸ” Hint

    Use the matrix() function with the data argument set to 1:9, nrow set to 3, and ncol set to 3.

    πŸ”‘ Solution
    m <- matrix(data = 1:9, nrow = 3, ncol = 3)
    

    Task 3.2: Selecting Elements from a Matrix

    Using the matrix created in the previous step, select the element in the 2nd row and 3rd column.

    πŸ” Hint

    Use the square brackets [] to select elements from a matrix. The row number comes first, followed by the column number, separated by a comma. So, to select the element in the 2nd row and 3rd column, use m[2,3].

    πŸ”‘ Solution
    m[2,3]
    

    Task 3.3: Creating an Array

    Create a 3-dimensional array with dimensions 2x2x2 and fill it with numbers from 1 to 8 using the array() function. Assign the array to a variable called a.

    πŸ” Hint

    Use the array() function with the data argument set to 1:8 and dim set to c(2,2,2).

    πŸ”‘ Solution
    a <- array(data = 1:8, dim = c(2,2,2))
    

    Task 3.4: Selecting Elements from an Array

    Using the array created in the previous task, select the element in the 1st row, 2nd column, and 2nd layer.

    πŸ” Hint

    Use the square brackets [] to select elements from an array. The row number comes first, followed by the column number, and then the layer number, all separated by commas. So, to select the element in the 1st row, 2nd column, and 2nd layer, use a[1,2,2].

    πŸ”‘ Solution
    a[1,2,2]
    

    Task 3.5: Creating a List

    Create a list containing a numeric vector, a character vector, and a logical vector using the list() function. Assign the list to a variable named l

    πŸ” Hint

    Use the list() function and pass in a numeric vector (e.g., c(1,2,3)), a character vector (e.g., c('a','b','c')), and a logical vector (e.g., c(TRUE,FALSE,TRUE)).

    πŸ”‘ Solution
    l <- list(c(1,2,3), c('a','b','c'), c(TRUE,FALSE,TRUE))
    

    Task 3.6: Selecting Elements from a List

    Using the list created in the previous task, select the 2nd element (the character vector).

    πŸ” Hint

    Use double square brackets [[]] to select elements from a list. The index of the element you want to select goes inside the brackets.

    πŸ”‘ Solution
    l[[2]]
    
  4. Challenge

    Working with Data Frames

    Working with Data Frames

    To review the concepts covered in this step, please refer to the Working with Data Frames module of the Programming with R course.

    Working with data frames is important because they are the most commonly used data structure in R for data analysis. This step will help you practice creating and manipulating data frames.

    Let's delve into the world of data frames in R. The goal here is to understand how to create data frames, insert data into them, and manipulate them. You will use the data.frame() function to create data frames, and practice selecting elements from them, adding rows and columns to them, and using the tidyverse package to manipulate them.


    Task 4.1: Create a Data Frame

    Create a data frame named df with three columns: name, age, and gender. The name column should contain the names 'John', 'Jane', and 'Joe'. The age column should contain the ages 23, 25, and 22. The gender column should contain the genders 'Male', 'Female', and 'Male'.

    πŸ” Hint

    Use the data.frame() function to create a data frame. You can specify the columns as arguments in the form column_name = c(values). Remember to use the c() function to create vectors of values for each column.

    πŸ”‘ Solution
    df <- data.frame(
      name = c('John', 'Jane', 'Joe'),
      age = c(23, 25, 22),
      gender = c('Male', 'Female', 'Male')
    )
    

    Task 4.2: Select Elements from a Data Frame

    Select the age column from the df data frame and assign it to a variable named ages.

    πŸ” Hint

    You can select a column from a data frame using the $ operator followed by the column name.

    πŸ”‘ Solution
    ages <- df$age
    

    Task 4.3: Add a Row to a Data Frame

    Add a new row to the df data frame with the name 'Jill', age 24, and gender 'Female'.

    πŸ” Hint

    Use the rbind() function to add a new row to a data frame. The new row should be another data frame in the form data.frame(column1 = value1, column2 = value2, ...). Remember to reassign the result to df to update the data frame.

    πŸ”‘ Solution
    new_row <- data.frame(name = 'Jill', age = 24, gender = 'Female')
    df <- rbind(df, new_row)
    

    Task 4.4: Add a Column to a Data Frame

    Add a new column named income to the df data frame with the values 50000, 60000, 55000, and 58000.

    πŸ” Hint

    You can add a new column to a data frame by using the $ operator followed by the new column name and assigning a vector of values to it.

    πŸ”‘ Solution
    df$income <- c(50000, 60000, 55000, 58000)
    

    Task 4.5: Manipulate a Data Frame with tidyverse

    Load the tidyverse package (it is already installed in this environment). Then use the filter() function to select the rows from the df data frame where age is greater than 23. Assign the result to a new data frame named df_filtered.

    πŸ” Hint

    Load the tidyverse package with library(tidyverse). You can use the filter() function from the tidyverse package to select rows based on a condition. The condition should be in the form column > value. Use the %>% operator to pipe the data frame into the filter() function.

    πŸ”‘ Solution
    library('tidyverse')
    
    df_filtered <- df %>% 
      filter(age > 23)
    
  5. Challenge

    Managing Control Statements

    Managing Control Statements

    To review the concepts covered in this step, please refer to the Managing Control Statements module of the Programming with R course.

    Understanding control statements is important because they allow you to control the flow of execution in your program. This step will help you practice using different types of control statements in R, including if, else, and switch statements, and for, while, and repeat loops.

    Let's practice controlling the flow of execution in your R programs. The goal here is to understand how to use different types of control statements in R, including if, else, and switch statements, and for, while, and repeat loops. You will practice writing conditional statements, using the switch command, and creating different types of loops.


    Task 5.1: Creating an If-Else Statement

    Create a numeric variable named num and assign the value 10. Write an if-else statement that prints 'Greater' if num is greater than 100 and 'Equal or Less' if not.

    πŸ” Hint

    The syntax for if-else in R is:

    if (condition) {
      #a
    } else {
      #b
    }
    

    Use the > operator to check if the number is greater than 100.

    πŸ”‘ Solution
    num <- 10
    
    if (num > 100) {
      print('Greater')
    } else {
      print('Equal or Less')
    }
    

    Task 5.2: Using the Switch Statement

    Create a character variable named month_name and assign the value "January". Create a switch statement to print the abbreviation of any given month_name based on its full name (Jan for January, Feb for February, etc.).

    πŸ” Hint

    Use the switch function with month_name as the first argument. Each subsequent argument should match the name of a month with the abbreviation (e.g., "January" = "Jan")

    πŸ”‘ Solution
    month_name <- "January"
    
    switch(month_name,
    "January" = "Jan",
     "February" = "Feb",
     "March" = "Mar",
     "April" = "Apr",
     "May" = "May",
     "June" = "Jun",
     "July" = "Jul",
     "August" = "Aug",
     "September" = "Sep",
     "October" = "Oct",
     "November" = "Nov",
     "December" = "Dec")
    

    Task 5.3: Creating a For Loop

    Write a for loop that prints the numbers from 1 to 10.

    πŸ” Hint

    The syntax of a for loop in R is:

    for (variable in sequence) {
      # code to execute during each iteration
    }
    

    Use the : operator to create the sequence from 1 to 10. Within the loop, print the variable.

    πŸ”‘ Solution
    for (i in 1:10) {
      print(i)
    }
    

    Task 5.4: Creating a While Loop

    Write a while loop that prints the numbers from 1 to 10.

    πŸ” Hint

    The syntax for a while loop in R is:

    while (condition) {
      # code to execute as long as the condition is true
    }
    

    Use a while loop with the condition i <= 10. In the loop, print i and then increment it by 1 by assigning i + 1 to i.

    Don't forget to initialize the value of i before you start the loop.

    πŸ”‘ Solution
    i <- 1
    
    while (i <= 10) {
      print(i)
      i <- i + 1
    }
    

    Task 5.5: Creating a Repeat Loop

    Write a repeat loop that prints the numbers from 1 to 10 and then breaks.

    πŸ” Hint

    The syntax for a repeat loop is:

    repeat {
      # code to execute
      if (condition) {
        break
      }
    }
    

    In the loop, print i, increment it by 1, and then break if i is greater than 10.

    Don't forget to initialize the value of i before you start the loop.

    πŸ”‘ Solution
    i <- 1
    
    repeat {
      print(i)
      i <- i + 1
      if (i > 10) {
        break
      }
    }
    
  6. Challenge

    Building Your First Function

    Building Your First Function

    To review the concepts covered in this step, please refer to the Building Your First Function module of the Programming with R course.

    Understanding how to create functions is important because functions allow you to write reusable code and make your programs more modular and efficient. This step will help you practice creating your own functions in R.

    Let's wrap up our practice session by building your first function in R. The goal here is to understand the components of a function and how to create one. You will practice writing a function, passing data as input to the function, and using control statements within the function.


    Task 6.1: Creating a Basic Function

    Create a function named my_function that takes one argument and returns the square of that argument.

    πŸ” Hint

    Use the ^ operator to square the input argument x.

    The syntax for a function in R is:

    function_name <- function(arg1, arg2, ...) {
      # function body
    }
    
    πŸ”‘ Solution
    my_function <- function(x) {
      return(x^2)
    }
    

    Task 6.2: Testing Your Function

    Test your function by calling it with the argument 5. Store the result in a variable named result, then print result.

    πŸ” Hint

    Call your function by using its name followed by parentheses. Inside the parentheses, put the argument you want to pass to the function.

    πŸ”‘ Solution
    result <- my_function(5)
    print(result)
    

    Task 6.3: Adding Control Statements to Your Function

    Modify your function to check if the input is numeric. If it is not, the function should return the message 'Input must be numeric.'

    πŸ” Hint

    Use the is.numeric() function to check if the input is numeric. Use an if statement to return the message if the input is not numeric.

    The ! operator in R is the logical NOT operator. It is used to invert the truth value of its following expression (e.g., !is.numeric(x)). Alternatively, you could use the equality operator to check for a FALSE value (e.g., is.numeric(x) == FALSE).

    πŸ”‘ Solution
    my_function <- function(x) {
      if (!is.numeric(x)) {
        return("Input must be numeric.")
      }
      return(x^2)
    }
    

    Note: The use of else is optional here because return() immediately exits the function and returns the specified value. This behavior effectively ends the function execution, making any subsequent code outside the if block act as if it were in an else block, without needing to explicitly use the else keyword.


    Task 6.4: Testing Your Modified Function

    Test your modified function by calling it with the argument 'five'. Store the result in a variable named result2. Then print result2.

    πŸ” Hint

    Call your function by using its name followed by parentheses. Inside the parentheses, put the argument you want to pass to the function.

    πŸ”‘ Solution
    result2 <- my_function('five')
    print(result2)
    

What's a lab?

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Provided environment for hands-on practice

We will provide the credentials and environment necessary for you to practice right within your browser.

Guided walkthrough

Follow along with the author’s guided walkthrough and build something new in your provided environment!

Did you know?

On average, you retain 75% more of your learning if you get time for practice.