Show/Hide Code
print("Hello, World!")A Practical Introduction to R Programming
Before writing any code, let’s get comfortable with the tool we will be using R Markdown. Think of it as a smart document where you can write normal text and run R code, and see the results all in the same place. It is like a notebook and a word processor combined.
Before doing anything else, save your file: File → Save (or Ctrl + S / Cmd + S). Give it a simple name with no spaces, e.g., my_first_r_markdown.Rmd.
Your RStudio screen is divided into four panels:
In R Markdown, R code lives inside a special block called a code chunk. It looks like this:
```{{r}}
# Your R code goes here
print("Hello!")
```To insert a new code chunk, press:
Ctrl + Alt + I (Windows / Linux)Cmd + Option + I (macOS)Or click the green + C button in the toolbar.
To run a single code chunk, click the green ▶ play button on the right side of the chunk, or press Ctrl + Shift + Enter.
Ctrl + Enter (Windows) / Cmd + Enter (Mac) — Runs only the line where your cursor is. You will use this all the time when testing code quickly!
Knitting means converting your R Markdown file into a nice finished document (Word, PDF, or HTML). Click the Knit button at the top of the editor, or press Ctrl + Shift + K.
Every time you knit, R re-runs all the code in your document from top to bottom. This is a good habit because it ensures your document is fully reproducible.
Every programmer starts with the same thing — making the computer display a message. Let’s do that now.
print() FunctionThe print() function tells R to display something on the screen. Type the following into a code chunk and press the ▶ button:
print("Hello, World!")Output:
[1] "Hello, World!"
The [1] at the start of the output simply means this is the first element of the result. You will see this in almost every R output — don’t worry about it for now, it is just R labelling its results.
Let’s try a few more lines:
print("My name is Mushikiwabo")
print("I am learning R.")
print("This is exciting!")Output:
[1] "My name is Mushikiwabo"
[1] "I am learning R."
[1] "This is exciting!"
Congratulations, you just wrote your first lines of R code!
cat() Function, Cleaner Outputcat() (short for concatenate and print) displays text without the [1] label, making output look cleaner:
cat("Hello, World!\n")
cat("I am learning R.\n")Output:
Hello, World!
I am learning R.
\n means new line. It tells R to move to the next line after printing. Try removing it and see what happens!
A comment is a line that R ignores when running your code. Comments start with a # symbol and are used to explain your code to yourself and others:
# This is a comment and R will NOT run this line
print("But R WILL run this line")
# Always label what your code is doing
print("Section 1 Complete!")Get into the habit of writing comments. Even experienced programmers use them to keep their code readable. A good comment explains why you did something, not just what you did.
A variable is like a labelled box where you store a piece of information. You give the box a name, put something inside it, and then refer to it by name whenever you need it.
<-In R, we store values into variables using <- (a less than sign followed by a dash). Read it as “gets”:
name <- "Mutsinzi"
age <- 32
district <- "Rubavu"Here, name gets the value "Mutsinzi", age gets 32, and so on.
Press Alt + - (Windows/Linux) or Option + - (Mac) to type <- instantly. You will use this constantly in R
Just type the variable name in a chunk and run it — R will display its contents:
name
age
districtOutput:
[1] "Mutsinzi"
[1] 32
[1] "Rubavu"
Or use print() or cat():
print(name)
cat("I live in", district, "\n")paste()Use paste() to join variables and text together:
name <- "Mutsinzi"
age <- 32
district <- "Rubavu"
cat(paste("My name is", name), "\n")
cat(paste("I am", age, "years old"), "\n")
cat(paste("I live in", district), "\n")Output:
My name is Mutsinzi
I am 32 years old
I live in Rubavu
You can change what is stored in a variable at any time:
score <- 0
cat("Starting score:", score, "\n")
score <- 10
cat("Updated score:", score, "\n")Output:
Starting score: 0
Updated score: 10
R handles several types of data. The most common are:
| Type | Example | What It Is |
|---|---|---|
character |
"Hello" |
Text (always in quotes) |
numeric |
42, 3.14 |
Numbers |
logical |
TRUE, FALSE |
Yes/No, True/False values |
# Check what type a variable is using class()
name <- "Mutsinzi"
age <- 32
adult <- TRUE
class(name)
class(age)
class(adult)Output:
[1] "character"
[1] "numeric"
[1] "logical"
Variable names in R:
age ✅ 1age ❌first_name, score.1Name and name are two different variablesstudent_age is better than xR was built for mathematics and statistics, so it works as a very powerful calculator straight out of the box.
# Addition
10 + 5
# Subtraction
10 - 7
# Multiplication
10 * 4
# Division
20 / 5Output:
[1] 15
[1] 3
[1] 40
[1] 4
# Exponent (power): 4 to the power of 2
4 ^ 2
# Integer division (quotient only)
17 %/% 5
# Modulo (remainder only)
17 %% 5
# Square root
sqrt(25)
# Absolute value
abs(-42)Output:
[1] 16
[1] 3
[1] 2
[1] 5
[1] 42
price <- 150
quantity <- 4
discount <- 20
subtotal <- price * quantity
total <- subtotal - discount
cat("Subtotal :", subtotal, "\n")
cat("Discount :", discount, "\n")
cat("Total :", total, "\n")Output:
Subtotal : 600
Discount : 20
Total : 580
pi_value <- 3.14159265
round(pi_value, 2) # Round to 2 decimal places
round(pi_value, 4) # Round to 4 decimal places
ceiling(pi_value) # Round UP to nearest whole number
floor(pi_value) # Round DOWN to nearest whole numberOutput:
[1] 3.14
[1] 3.1416
[1] 4
[1] 3
# Change the values and re-run to see new results
hours_worked <- 40
hourly_rate <- 15 # amafrw bakwishyura cg bakubarira ku isaha
tax_rate <- 0.20 # 20% tax
gross_pay <- hours_worked * hourly_rate
tax <- gross_pay * tax_rate
net_pay <- gross_pay - tax
cat("Gross Pay : $", gross_pay, "\n")
cat("Tax (20%) : $", tax, "\n")
cat("Net Pay : $", net_pay, "\n")In R, a vector is the most fundamental way to store multiple values of the same type in a single variable. Think of it like a column in a spreadsheet.
c()c() stands for combine. It groups values together into a vector:
# A vector of numbers
scores <- c(88, 45, 95, 61, 73, 39, 82)
# A vector of text
fruits <- c("apple", "banana", "mango", "amatunda")
# A vector of logical values
passed <- c(TRUE, FALSE, TRUE, TRUE, FALSE)
scores
fruits
passedOutput:
[1] 88 45 95 61 73 39 82
[1] "apple" "banana" "mango" "amatunda"
[1] TRUE FALSE TRUE TRUE FALSE
Use square brackets [ ] to access specific items. R counts from 1 (not 0):
fruits <- c("apple", "banana", "mango", "amatunda")
fruits[1] # First item
fruits[3] # Third item
fruits[2:4] # Items 2 through 4 (a "slice")Output:
[1] "apple"
[1] "mango"
[1] "banana" "mango" "amatunda"
scores <- c(88, 45, 95, 61, 73, 39, 82)
length(scores) # How many values are there?
sum(scores) # Add all values
mean(scores) # Calculate the average
max(scores) # Highest value
min(scores) # Lowest value
sort(scores) # Sort from smallest to largestOutput:
[1] 7
[1] 483
[1] 69
[1] 95
[1] 39
[1] 39 45 61 73 82 88 95
One of R’s most powerful features: you can apply a calculation to every element of a vector in a single step, no loop needed.
prices <- c(100, 200, 150, 80, 300)
# Add 10 to every price
prices + 10
# Apply a 15% discount to every price
prices * 0.85
# Is each price above 100?
prices > 100Output:
[1] 110 210 160 90 310
[1] 85 170 127.5 68 255
[1] FALSE TRUE TRUE FALSE TRUE
students <- c("Mugisha", "Bob", "Uwase", "David", "Delila")
scores <- c(88, 45, 95, 61, 73)
cat("Number of students :", length(students), "\n")
cat("Class average :", mean(scores), "\n")
cat("Highest score :", max(scores), "\n")
cat("Lowest score :", min(scores), "\n")Output:
Number of students : 5
Class average : 72.4
Highest score : 95
Lowest score : 45
if StatementsIn real life, we constantly make decisions based on conditions: “If it is raining, I will take an umbrella.” R does the same with if statements.
if Statementage <- 20
if (age >= 18) {
print("You are an adult.")
}Output:
[1] "You are an adult."
In R, the code that belongs inside an if block is wrapped in curly braces { }. Everything between { and } only runs if the condition is TRUE.
if / elseage <- 15
if (age >= 18) {
cat("You are allowed to vote.\n")
} else {
cat("You are not old enough to vote yet.\n")
}Output:
You are not old enough to vote yet.
if / else if / else (Multiple Conditions)score <- 72
if (score >= 90) {
cat("Grade: A - Excellent\n")
} else if (score >= 75) {
cat("Grade: B - Very Good\n")
} else if (score >= 60) {
cat("Grade: C - Good\n")
} else {
cat("Grade: F - Fail\n")
}Output:
Grade: C — Good
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
Equal to | 5 == 5 |
TRUE |
!= |
Not equal to | 5 != 3 |
TRUE |
> |
Greater than | 7 > 3 |
TRUE |
< |
Less than | 2 < 9 |
TRUE |
>= |
Greater than or equal | 5 >= 5 |
TRUE |
<= |
Less than or equal | 3 <= 4 |
TRUE |
age <- 22
income <- 3000
# AND: both conditions must be TRUE
if (age >= 18 & income >= 2000) {
cat("Loan application: APPROVED\n")
}
# OR: at least one condition must be TRUE
if (age < 18 | income < 1000) {
cat("Loan application: REJECTED\n")
} else {
cat("Loan application: APPROVED\n")
}# Change the temperature and rerun to see a different message
temperature <- 30
if (temperature > 35) {
cat("It is very hot. Stay hydrated!\n")
} else if (temperature > 25) {
cat("It is warm. A great day to go out!\n")
} else if (temperature > 15) {
cat("It is mild. Bring a light jacket.\n")
} else {
cat("It is cold. Dress warmly!\n")
}A loop lets you repeat a block of code automatically without copying and pasting. This is one of the most important ideas in all of programming.
for LoopA for loop repeats code for each item in a vector:
fruits <- c("apple", "banana", "mango", "amatunda")
for (fruit in fruits) {
print(fruit)
}Output:
[1] "apple"
[1] "banana"
[1] "mango"
[1] "amatunda"
Think of it as: “For each fruit in my list of fruits, print that fruit.”
seq()for (number in 1:5) {
cat("Step", number, "\n")
}Output:
Step 1
Step 2
Step 3
Step 4
Step 5
1:5 is R shorthand for the sequence 1, 2, 3, 4, 5.
students <- c("Alice", "Bob", "Carol", "David")
for (student in students) {
cat(paste("Hello,", student, "! Welcome to class.\n"))
}Output:
Hello, Alice ! Welcome to class.
Hello, Bob ! Welcome to class.
Hello, Carol ! Welcome to class.
Hello, David ! Welcome to class.
if (Putting It All Together!)scores <- c(88, 45, 95, 61, 73, 39, 82)
for (score in scores) {
if (score >= 75) {
cat("Score", score, "→ PASS ✅\n")
} else {
cat("Score", score, "→ FAIL ❌\n")
}
}Output:
Score 88 → PASS ✅
Score 45 → FAIL ❌
Score 95 → PASS ✅
Score 61 → FAIL ❌
Score 73 → FAIL ❌
Score 39 → FAIL ❌
Score 82 → PASS ✅
A common pattern: start with an empty result, and build it up as the loop runs.
scores <- c(88, 45, 95, 61, 73, 39, 82)
passing <- c() # Start with an empty vector
for (score in scores) {
if (score >= 75) {
passing <- c(passing, score) # Add passing score to the vector
}
}
cat("Passing scores:", passing, "\n")
cat("Number who passed:", length(passing), "\n")Output:
Passing scores: 88 95 82
Number who passed: 3
# This prints a times table for any number you choose
# Change the number below and re-run!
number <- 7
cat(paste("--- Times Table for", number, "---\n"))
for (i in 1:10) {
result <- number * i
cat(number, "x", i, "=", result, "\n")
}Output (for number = 7):
--- Times Table for 7 ---
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
One of R’s greatest strengths is creating beautiful charts and graphs with very little code. Let’s create your first visualizations using R’s built-in plot() function — no extra packages needed!
# Student scores
students <- c("Alice", "Bob", "Carol", "David", "Eve")
scores <- c(88, 45, 95, 61, 73)
barplot(
scores,
names.arg = students,
col = "steelblue",
main = "Student Scores",
xlab = "Student",
ylab = "Score",
ylim = c(0, 100)
)# Monthly temperatures (°C)
months <- 1:12
temperature <- c(18, 20, 23, 26, 28, 30, 29, 29, 27, 24, 21, 18)
plot(
months,
temperature,
type = "b", # "b" = both points AND lines
col = "tomato",
pch = 16, # Filled circle points
main = "Monthly Average Temperature",
xlab = "Month",
ylab = "Temperature (°C)",
xaxt = "n" # We'll add custom x-axis labels
)
# Add month name labels on the x-axis
axis(1, at = 1:12,
labels = c("Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"))A histogram shows how data is distributed — how often values fall into different ranges:
# Simulate 200 exam scores (normally distributed around 70)
set.seed(42)
exam_scores <- round(rnorm(200, mean = 70, sd = 12))
hist(
exam_scores,
col = "mediumpurple",
border = "white",
main = "Distribution of Exam Scores",
xlab = "Score",
ylab = "Number of Students",
breaks = 15
)
# Add a vertical line at the mean
abline(v = mean(exam_scores), col = "red", lwd = 2, lty = 2)set.seed() makes random numbers reproducible — every time you run the code you get the same “random” numbers. The number 42 is just a convention; you can use any number you like.
# Create your own bar chart!
# Replace the items and values below with anything you like
items <- c("Football", "Basketball", "Tennis", "Swimming", "Running")
fans <- c(320, 180, 95, 140, 210)
barplot(
fans,
names.arg = items,
col = c("tomato", "steelblue", "seagreen", "gold", "mediumpurple"),
main = "Favourite Sports Survey",
xlab = "Sport",
ylab = "Number of Fans",
border = "white"
)You have made it through your first R journey — well done!
Here is a summary of everything you have learned:
| Chapter | Concept | What It Does |
|---|---|---|
| 2 | print(), cat() & Comments |
Displays output; adds notes to code |
| 3 | Variables & <- |
Stores and labels information |
| 4 | Numbers & Math | Performs calculations and rounding |
| 5 | Vectors | Groups multiple values; the heart of R |
| 6 | if Statements |
Makes decisions based on conditions |
| 7 | for Loops |
Repeats actions automatically |
| 8 | Plots | Visualizes data with bar, line, and histogram charts |
The best way to learn R is by experimenting. Here are some ideas to try on your own in a new R Markdown file:
mean(), min(), and max()if/else if/else block that takes a temperature and prints whether it is “Freezing”, “Cold”, “Warm”, or “Hot”for loop to print the first 10 multiples of any number you choose| Resource | Link |
|---|---|
| Intermediate R Programming | Intermediate R Programming by Prosper |
| Posit Community Forum | Posit Community |
| More from Prosper | Prosper |
Once you are comfortable with these basics, explore the tidyverse.
Tidyverse is a powerful collection of R packages for data manipulation and visualization. Start with ggplot2 for beautiful charts and dplyr for working with data tables. Install them with: install.packages("tidyverse")
Every expert R programmer was once a complete beginner. The most important thing is to keep experimenting, make mistakes, and never stop asking “what happens if I change this?”. Happy coding!