- Lab
- Data

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.

Path Info
Table of Contents
-
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 theclass()
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 variablenum_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 variablechar_var
.π Solution
char_var <- 'Hello, R!'
Task 1.3: Creating a Logical Variable
Create a logical variable named
log_var
and assign the boolean valueTRUE
to it.π Hint
Use the assignment operator
<-
to assign the boolean valueTRUE
to the variablelog_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 theclass()
function.π Hint
Pass the variable
num_var
as an argument to theclass()
function.π Solution
class(num_var)
-
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 thefactor()
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 thec()
function.π Hint
Use the
c()
function to concatenate the numbers 1 through 10 into a vector. The syntax isc(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 tomy_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 thefactor()
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 syntaxc('value1', 'value2', ...)
.
By default, the order of factor levels will be alphabetical β to supply an explicit level order, pass a second argument calledlevels
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 namedordered_vector
.π Hint
You can order a vector in ascending order using the
sort()
function. The syntax issort(vector)
.
To preserve the new order, make sure to assign the output ofsort()
to a new variable namedordered_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 ofmy_vector
andanother_vector
and assign the result to a new vector namedintersection_vector
.π Hint
You can find the intersection of two vectors using the
intersect()
function. The syntax isintersect(vector1, vector2)
.
You can use a colon:
to select a consecutive sequence of numbers. In this case, use5:15
.π Solution
another_vector <- 5:15 intersection_vector <- intersect(my_vector, another_vector)
-
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()
, andlist()
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 namedm
.π Hint
Use the
matrix()
function with thedata
argument set to1:9
,nrow
set to3
, andncol
set to3
.π 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, usem[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 calleda
.π Hint
Use the
array()
function with thedata
argument set to1:8
anddim
set toc(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, usea[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 namedl
π 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]]
-
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 thetidyverse
package to manipulate them.
Task 4.1: Create a Data Frame
Create a data frame named
df
with three columns:name
,age
, andgender
. Thename
column should contain the names 'John', 'Jane', and 'Joe'. Theage
column should contain the ages 23, 25, and 22. Thegender
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 formcolumn_name = c(values)
. Remember to use thec()
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 thedf
data frame and assign it to a variable namedages
.π 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 formdata.frame(column1 = value1, column2 = value2, ...)
. Remember to reassign the result todf
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 thedf
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 thefilter()
function to select the rows from thedf
data frame whereage
is greater than 23. Assign the result to a new data frame nameddf_filtered
.π Hint
Load the
tidyverse
package withlibrary(tidyverse)
. You can use thefilter()
function from thetidyverse
package to select rows based on a condition. The condition should be in the formcolumn > value
. Use the%>%
operator to pipe the data frame into thefilter()
function.π Solution
library('tidyverse') df_filtered <- df %>% filter(age > 23)
-
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' ifnum
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 givenmonth_name
based on its full name (Jan for January, Feb for February, etc.).π Hint
Use the
switch
function withmonth_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, printi
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 ifi
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 } }
-
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 argumentx
.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 printresult
.π 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 anif
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 becausereturn()
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 printresult2
.π 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.