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.
By the end of this module, you should be able to:
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.
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:
To display the values, use the print() function:
print(student_name) print(student_age)
Expected output:
[1] "Ade" [1] 13
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.
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.
Data types describe the kind of information stored in a variable.
R supports different data types. Here are some important ones:
Numeric values are numbers that can contain decimal points.
price <- 2500.50 temperature <- 36.5
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
Character values are text, such as names, places, and product descriptions. They are written inside quotation marks.
student <- "Chika" city <- "Ibadan" product <- "Rice"
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.
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.
R can perform mathematical calculations just like an ordinary calculator.
Here are some common mathematical operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | Addition | 10 + 5 | 15 |
| - | Subtraction | 10 - 5 | 5 |
| * | Multiplication | 10 * 5 | 50 |
| / | Division | 10 / 5 | 2 |
| ^ | Power | 2 ^ 3 | 8 |
| %% | Remainder | 10 %% 3 | 1 |
| %/% | Whole-number division | 10 %/% 3 | 3 |
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.
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.
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"
The nchar() function counts the number of characters in a text value, including spaces.
message <- "Hello World" nchar(message)
Result: 11
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 to | 10 == 10 | TRUE |
| != | Not equal to | 10 != 5 | TRUE |
| > | Greater than | 10 > 5 | TRUE |
| < | Less than | 5 < 10 | TRUE |
| >= | Greater than or equal to | 10 >= 10 | TRUE |
| <= | Less than or equal to | 5 <= 10 | TRUE |
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.
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.
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:
Incorrect:
name <- "Ade
Correct:
name <- "Ade"
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)
Incorrect:
print("Hello"
Correct:
print("Hello")
Use the correct assignment operator when storing values.
sales <- 50000 print(sales)
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.
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 |
|---|---|
| Ade | 75 |
| Chika | 85 |
| Tunde | 60 |
| Fatima | 90 |
| Emeka | 70 |
Complete these activities using R:
# 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)
In this module, you learned:
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.