Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Introduction to R for Data Analysis ยท Lesson 4 of 9

Module Three

๐Ÿ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
4

Module 3: R Programming Basics

Module Introduction

In the previous module, you learned how to install R and RStudio, explore the RStudio interface, and write your first R command.

Now it is time to understand how R programming works. You will learn how to create variables, store information, perform calculations, work with text and numbers, and write simple instructions that R can understand.

Imagine you are helping a supermarket in Lagos calculate its daily sales. Instead of using a calculator every time, you can write instructions in R to perform the calculations automatically.

Learning Objectives

By the end of this module, you should be able to:

  • Understand basic R programming syntax.
  • Create and use variables.
  • Assign values to variables.
  • Perform mathematical calculations.
  • Work with text and numeric values.
  • Write comments in R.
  • Identify and correct simple programming errors.

1. Understanding R Syntax

Syntax refers to the rules used when writing instructions in a programming language.

Just as English has grammar rules, R has rules that must be followed when writing commands. If you write a command incorrectly, R may display an error instead of producing the expected result.

For example, this is a correct R command:

print("Hello, welcome to R")

It tells R to display the message:

[1] "Hello, welcome to R"

However, the following command is incorrect because the closing quotation mark is missing:

print("Hello, welcome to R)

R needs the quotation marks and brackets to be correctly placed.

Important R Syntax Rules

  • Use quotation marks around text values.
  • Use brackets correctly when calling functions.
  • Write variable names consistently.
  • Use the assignment operator to store values.
  • Check spelling when writing function names.

2. Understanding Variables in R

A variable is a named container used to store information in a computer program.

Think of a variable as a labelled box. You can put a value inside the box and use it whenever you need it.

For example, imagine a student named Ade is 13 years old. You can store Ade's name and age in two variables.

student_name <- "Ade"
student_age <- 13

Here is what the code means:

  • student_name: The name of the first variable.
  • "Ade": The text stored inside the variable.
  • student_age: The name of the second variable.
  • 13: The number stored inside the variable.

To display the values, use the print() function:

print(student_name)
print(student_age)

Expected output:

[1] "Ade"
[1] 13

3. Assigning Values to Variables

In R, the assignment operator is commonly written as <-. It is used to store information in a variable.

For example:

price <- 5000
quantity <- 4

total <- price * quantity

print(total)

Result: 20000

This example calculates the total cost of four items that cost โ‚ฆ5,000 each.

You can also use the equals sign (=) for assignment in many situations, but the left arrow (<-) is commonly used in R programming.

Changing a Variable's Value

You can change the information stored inside a variable whenever necessary.

score <- 60

print(score)

score <- 85

print(score)

The first result is 60, while the second result is 85 because the variable's value was updated.

4. Understanding Data Types in R

Data types describe the kind of information stored in a variable.

R supports different data types. Here are some important ones:

A. Numeric

Numeric values are numbers that can contain decimal points.

price <- 2500.50
temperature <- 36.5

B. Integer

Integers are whole numbers without decimal points. In R, you can identify an integer by adding the letter L after the number.

age <- 13L
students <- 50L

C. Character

Character values are text, such as names, places, and product descriptions. They are written inside quotation marks.

student <- "Chika"
city <- "Ibadan"
product <- "Rice"

D. Logical

Logical values represent either TRUE or FALSE.

is_student <- TRUE
has_paid <- FALSE

For example, a school can use a logical value to record whether a student has paid examination fees.

Checking a Variable's Data Type

You can use the class() function to find out the type or class of an object.

age <- 13L
name <- "Ade"
price <- 2500.50

class(age)
class(name)
class(price)

R will display the class of each variable.

5. Basic Mathematical Operations in R

R can perform mathematical calculations just like an ordinary calculator.

Here are some common mathematical operators:

Operator Meaning Example Result
+Addition10 + 515
-Subtraction10 - 55
*Multiplication10 * 550
/Division10 / 52
^Power2 ^ 38
%%Remainder10 %% 31
%/%Whole-number division10 %/% 33

Practical Example: Calculating Supermarket Sales

Imagine a supermarket sells 10 bags of rice at โ‚ฆ45,000 each.

price_per_bag <- 45000
quantity_sold <- 10

total_sales <- price_per_bag * quantity_sold

print(total_sales)

Result: 450000

The supermarket made โ‚ฆ450,000 from the rice sales.

6. Working with Text in R

R can also store and work with text. Text values are called character data.

For example:

first_name <- "Ade"
last_name <- "Johnson"

full_name <- paste(first_name, last_name)

print(full_name)

Result: "Ade Johnson"

The paste() function joins text values together.

Joining Text with paste0()

You can also use paste0() to join text without automatically adding spaces between the values.

first_name <- "CRM"
last_name <- "Nuggets"

brand_name <- paste0(first_name, last_name)

print(brand_name)

Result: "CRMNuggets"

Finding the Length of Text

The nchar() function counts the number of characters in a text value, including spaces.

message <- "Hello World"

nchar(message)

Result: 11

7. Using Comparison Operators

Comparison operators help you compare two values. They are useful when checking whether a student passed an examination or whether a product has reached a particular sales target.

Operator Meaning Example Result
==Equal to10 == 10TRUE
!=Not equal to10 != 5TRUE
>Greater than10 > 5TRUE
<Less than5 < 10TRUE
>=Greater than or equal to10 >= 10TRUE
<=Less than or equal to5 <= 10TRUE

Example: A teacher wants to check whether a student scored at least 50 marks.

score <- 75

score >= 50

Result: TRUE

This means the student's score is greater than or equal to 50.

8. Using Comments in R

Comments are notes that explain what your code does. They help you understand your program, especially when it contains many instructions.

In R, comments begin with the hash symbol (#).

# Store the student's score
score <- 85

# Display the score
print(score)

R ignores comments when executing your program.

Comments are useful when working on large data analysis projects because they make your code easier to understand.

9. Understanding Basic R Errors

Sometimes, R may display an error when you write a command incorrectly. This is normal when learning programming.

Here are some common mistakes beginners make:

A. Missing Quotation Marks

Incorrect:

name <- "Ade

Correct:

name <- "Ade"

B. Incorrect Variable Name

If you create a variable called student_score but try to print students_score, R may report that the object cannot be found.

Correct example:

student_score <- 90

print(student_score)

C. Missing Brackets

Incorrect:

print("Hello"

Correct:

print("Hello")

D. Using the Wrong Assignment Symbol

Use the correct assignment operator when storing values.

sales <- 50000
print(sales)

10. Practical Data Analysis Example

Imagine you are helping a small supermarket in Ibadan analyse its daily sales.

The supermarket sells rice, beans, and milk. The following code calculates its total sales.

# Store product prices
rice <- 50000
beans <- 30000
milk <- 20000

# Calculate total sales
total_sales <- rice + beans + milk

# Calculate average sales
average_sales <- total_sales / 3

# Display the results
print(total_sales)
print(average_sales)

Total Sales: โ‚ฆ100,000

Average Sales: โ‚ฆ33,333.33

This simple example shows how R can help businesses calculate and understand their sales information.

11. Practical Exercise

It is time to practise what you have learned.

Imagine you are analysing examination results for five students in a school in Lagos.

Student Score
Ade75
Chika85
Tunde60
Fatima90
Emeka70

Complete these activities using R:

  1. Create a variable called student_name and store the name "Ade".
  2. Create a variable called student_age and store the number 13.
  3. Create a variable called score and store the number 75.
  4. Calculate the total of 75, 85, 60, 90, and 70.
  5. Calculate the average score of the five students.
  6. Check whether 75 is greater than or equal to 50.
  7. Join the words "Data" and "Analysis" using paste().
  8. Write a comment explaining what your code does.

Sample Solution

# Create student variables
student_name <- "Ade"
student_age <- 13
score <- 75

# Calculate total examination scores
total_score <- 75 + 85 + 60 + 90 + 70

# Calculate average score
average_score <- total_score / 5

# Check if the score is a pass
passed <- score >= 50

# Join two words
course_name <- paste("Data", "Analysis")

# Display the results
print(student_name)
print(student_age)
print(total_score)
print(average_score)
print(passed)
print(course_name)

12. Module Summary

In this module, you learned:

  • R syntax and the rules for writing commands.
  • How to create and use variables.
  • How to assign values using the <- operator.
  • Different data types, including numeric, integer, character, and logical.
  • How to perform mathematical calculations.
  • How to work with text using paste(), paste0(), and nchar().
  • How to compare values using comparison operators.
  • How to write comments and identify common errors.

What Is Next?

In Module 4, we will learn about Data Structures in R. You will discover how R organises information using vectors, lists, matrices, arrays, data frames, and factors.

Keep practising! Programming becomes easier when you write and test your own code.

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (โ‚ฆ2,000 or 20,000 coins), and get a verified certificate with your name on it.

๐ŸŽ“ Sign Up to Get Certified
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
โ†’