Your First Steps in R

A Practical Introduction to R Programming

Author

Prosper AYINEBYONA

Published

March 16, 2026

1 Getting Started with R Markdown

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.

1.1 Creating Your First R Markdown File

  1. Open RStudio
  2. Go to File → New File → R Markdown…
  3. Give your document a Title (e.g., “My First R Script”) and enter your name
  4. Select HTML as the output format and click OK
  5. A new file will open with some example content, this is your R Markdown document
Save your file first!

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.

1.2 Understanding the Interface

Your RStudio screen is divided into four panels:

1.3 Understanding Code Chunks

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.

Your most used shortcut

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!

1.4 Knitting Your Document

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.

Note

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.


2 Your Very First Lines of R Code

Every programmer starts with the same thing — making the computer display a message. Let’s do that now.

2.1 The print() Function

The print() function tells R to display something on the screen. Type the following into a code chunk and press the ▶ button:

Show/Hide Code
print("Hello, World!")

Output:

[1] "Hello, World!"
What does [1] mean?

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:

Show/Hide Code
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!

2.2 The cat() Function, Cleaner Output

cat() (short for concatenate and print) displays text without the [1] label, making output look cleaner:

Show/Hide Code
cat("Hello, World!\n")
cat("I am learning R.\n")

Output:

Hello, World!
I am learning R.
What is ?

\n means new line. It tells R to move to the next line after printing. Try removing it and see what happens!

2.3 Adding Comments

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:

Show/Hide Code
# 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!")
Tip

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.


3 Variables (Storing Information)

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.

3.1 The Assignment Operator <-

In R, we store values into variables using <- (a less than sign followed by a dash). Read it as “gets”:

Show/Hide Code
name <- "Mutsinzi"
age  <- 32
district <- "Rubavu"

Here, name gets the value "Mutsinzi", age gets 32, and so on.

Keyboard shortcut for <-

Press Alt + - (Windows/Linux) or Option + - (Mac) to type <- instantly. You will use this constantly in R

3.2 Viewing a Variable’s Value

Just type the variable name in a chunk and run it — R will display its contents:

Show/Hide Code
name
age
district

Output:

[1] "Mutsinzi"
[1] 32
[1] "Rubavu"

Or use print() or cat():

Show/Hide Code
print(name)
cat("I live in", district, "\n")

3.3 Combining Variables and Text with paste()

Use paste() to join variables and text together:

Show/Hide Code
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

3.4 Updating a Variable

You can change what is stored in a variable at any time:

Show/Hide Code
score <- 0
cat("Starting score:", score, "\n")

score <- 10
cat("Updated score:", score, "\n")

Output:

Starting score: 0
Updated score: 10

3.5 Types of Data in R

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
Show/Hide Code
# 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"
Naming rules for variables

Variable names in R:

  • Must start with a letter: age ✅   1age
  • Can contain letters, numbers, dots, and underscores: first_name, score.1
  • Are case-sensitive: Name and name are two different variables
  • Should be meaningful: student_age is better than x

4 Numbers and Basic Math

R was built for mathematics and statistics, so it works as a very powerful calculator straight out of the box.

4.1 Basic Arithmetic

Show/Hide Code
# Addition
10 + 5

# Subtraction
10 - 7

# Multiplication
10 * 4

# Division
20 / 5

Output:

[1] 15
[1] 3
[1] 40
[1] 4

4.2 More Operations

Show/Hide Code
# 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

4.3 Math with Variables

Show/Hide Code
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

4.4 Rounding Numbers

Show/Hide Code
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 number

Output:

[1] 3.14
[1] 3.1416
[1] 4
[1] 3

4.5 Exercise 1

Show/Hide Code
# 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")

5 Vectors (Working with Multiple Values)

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.

5.1 Creating a Vector with c()

c() stands for combine. It groups values together into a vector:

Show/Hide Code
# 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
passed

Output:

[1] 88 45 95 61 73 39 82
[1] "apple"  "banana" "mango"  "amatunda"
[1]  TRUE FALSE  TRUE  TRUE FALSE

5.2 Accessing Elements

Use square brackets [ ] to access specific items. R counts from 1 (not 0):

Show/Hide Code
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"

5.3 Useful Vector Functions

Show/Hide Code
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 largest

Output:

[1] 7
[1] 483
[1] 69
[1] 95
[1] 39
[1] 39 45 61 73 82 88 95

5.4 Math on an Entire Vector at Once

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.

Show/Hide Code
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 > 100

Output:

[1] 110 210 160  90 310
[1]  85 170 127.5  68 255
[1] FALSE  TRUE  TRUE FALSE  TRUE

5.5 Example

Show/Hide Code
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

6 Making Decisions with if Statements

In 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.

6.1 Basic if Statement

Show/Hide Code
age <- 20

if (age >= 18) {
  print("You are an adult.")
}

Output:

[1] "You are an adult."
The curly braces { } matter!

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.

6.2 if / else

Show/Hide Code
age <- 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.

6.3 if / else if / else (Multiple Conditions)

Show/Hide Code
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

6.4 Comparison Operators

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

6.5 Logical Operators (Combining Conditions)

Show/Hide Code
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")
}

6.6 Exercise 2

Show/Hide Code
# 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")
}

7 Repeating Actions with Loops

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.

7.1 The for Loop

A for loop repeats code for each item in a vector:

Show/Hide Code
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.”

7.2 Looping Through Numbers with seq()

Show/Hide Code
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.

7.3 Doing Something Useful in a Loop

Show/Hide Code
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.

7.4 Combining a Loop with if (Putting It All Together!)

Show/Hide Code
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 ✅

7.5 Building a Result Inside a Loop

A common pattern: start with an empty result, and build it up as the loop runs.

Show/Hide Code
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

7.6 A Final Challenge — Try It Yourself!

Show/Hide Code
# 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

8 Your First Plot — Visualizing Data

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!

8.1 A Simple Bar Chart

Show/Hide Code
# 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)
)

8.2 A Line Chart

Show/Hide Code
# 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"))

8.3 A Histogram

A histogram shows how data is distributed — how often values fall into different ranges:

Show/Hide Code
# 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)
What is set.seed(42)?

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.

8.4 A Mini Exercise — Try It Yourself!

Show/Hide Code
# 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"
)

9 What’s Next?

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

9.1 Keep Practising

The best way to learn R is by experimenting. Here are some ideas to try on your own in a new R Markdown file:

  • Create a vector of the ages of 6 people you know, and calculate the average, minimum, and maximum age using mean(), min(), and max()
  • Write an if/else if/else block that takes a temperature and prints whether it is “Freezing”, “Cold”, “Warm”, or “Hot”
  • Create a bar chart showing your 5 favourite foods and how much you rate them out of 10
  • Use a for loop to print the first 10 multiples of any number you choose