R Exercises

Welcome to The Coding College! If you’re learning R programming, practicing with hands-on exercises is the best way to reinforce your skills. In this post, we provide a curated set of R exercises for beginners and intermediate learners to help you improve your programming, data analysis, and visualization skills.

Whether you’re new to R or want to solidify your understanding, these exercises cover essential R concepts, including:

  • Variables and Data Types
  • Conditional Statements
  • Loops and Functions
  • Data Frames and Matrices
  • Statistical Analysis and Visualization

Let’s dive into the exercises and build your R expertise step by step!

Beginner-Level R Exercises

1. Create Variables and Perform Arithmetic

Objective: Write a script that creates two variables, performs basic arithmetic operations, and prints the results.

# Exercise: Perform Arithmetic Operations
# Create two variables
num1 <- 15
num2 <- 5

# Perform operations
addition <- num1 + num2
subtraction <- num1 - num2
multiplication <- num1 * num2
division <- num1 / num2

# Print the results
print(paste("Addition:", addition))
print(paste("Subtraction:", subtraction))
print(paste("Multiplication:", multiplication))
print(paste("Division:", division))

2. Manipulate Vectors

Objective: Create a numeric vector, find its length, and calculate the mean, sum, and standard deviation.

# Exercise: Vector Manipulation
# Create a numeric vector
numbers <- c(10, 20, 30, 40, 50)

# Perform operations
vector_length <- length(numbers)
vector_mean <- mean(numbers)
vector_sum <- sum(numbers)
vector_sd <- sd(numbers)

# Print results
print(paste("Length:", vector_length))
print(paste("Mean:", vector_mean))
print(paste("Sum:", vector_sum))
print(paste("Standard Deviation:", vector_sd))

3. Use Conditional Statements

Objective: Check if a number is positive, negative, or zero.

# Exercise: Conditional Statements
# Define a number
number <- -10

# Check the number
if (number > 0) {
  print("The number is positive")
} else if (number < 0) {
  print("The number is negative")
} else {
  print("The number is zero")
}

Intermediate-Level R Exercises

4. Work with Data Frames

Objective: Create a data frame with student information and add a new column to calculate their grades.

# Exercise: Data Frames
# Create a data frame
students <- data.frame(
  Name = c("Alice", "Bob", "Charlie"),
  Marks = c(85, 90, 78)
)

# Add a new column for grades
students$Grade <- ifelse(students$Marks >= 90, "A", ifelse(students$Marks >= 80, "B", "C"))

# Print the updated data frame
print(students)

5. Create a Function

Objective: Write a function that calculates the factorial of a number.

# Exercise: Function for Factorial
# Define the factorial function
factorial_function <- function(n) {
  if (n == 0) {
    return(1)
  } else {
    return(n * factorial_function(n - 1))
  }
}

# Test the function
result <- factorial_function(5)
print(paste("Factorial of 5 is:", result))

6. Generate Plots

Objective: Create a scatter plot with labeled axes and a title.

# Exercise: Scatter Plot
# Define data
x <- c(1, 2, 3, 4, 5)
y <- c(10, 20, 30, 40, 50)

# Create the scatter plot
plot(x, y, main = "Scatter Plot Example", xlab = "X-Axis", ylab = "Y-Axis", col = "blue", pch = 16)

7. Analyze a Data Set

Objective: Load a built-in R dataset (e.g., mtcars) and calculate summary statistics.

# Exercise: Analyze mtcars Dataset
# Load the dataset
data("mtcars")

# Calculate summary statistics
summary_stats <- summary(mtcars)
print(summary_stats)

# Calculate mean MPG
mean_mpg <- mean(mtcars$mpg)
print(paste("Mean MPG:", mean_mpg))

Advanced-Level R Exercises

8. Perform Linear Regression

Objective: Fit a linear regression model to predict mpg based on wt in the mtcars dataset.

# Exercise: Linear Regression
# Load the dataset
data("mtcars")

# Fit a linear model
model <- lm(mpg ~ wt, data = mtcars)

# Print the model summary
print(summary(model))

9. Work with Time Series Data

Objective: Analyze and plot a time series dataset.

# Exercise: Time Series Analysis
# Create a time series
time_series <- ts(c(100, 120, 140, 130, 150), start = c(2020, 1), frequency = 12)

# Plot the time series
plot(time_series, main = "Time Series Example", xlab = "Time", ylab = "Value", col = "green")

10. Use dplyr for Data Manipulation

Objective: Filter and summarize data using the dplyr package.

# Exercise: dplyr Example
# Load the dplyr library
library(dplyr)

# Filter and summarize data
filtered_data <- mtcars %>%
  filter(cyl == 6) %>%
  summarize(Mean_MPG = mean(mpg), Mean_Horsepower = mean(hp))

# Print the result
print(filtered_data)

How to Practice R Exercises Effectively

  1. Set Clear Goals: Focus on one topic at a time, such as data manipulation, visualization, or statistical analysis.
  2. Use Online Platforms: Try an R Online Compiler to run your code without installing R locally.
  3. Explore Built-in Datasets: Use datasets like mtcars, iris, or airquality to practice real-world scenarios.
  4. Challenge Yourself: Modify the exercises by adding extra functionality or handling edge cases.

Conclusion

These R exercises will help you strengthen your understanding of R programming while applying concepts to real-world scenarios. Whether you’re practicing basic syntax or analyzing datasets, the hands-on approach is the best way to learn.

Leave a Comment