Module 10 - Computer Programs and R Mack-
down
Instructional Hours: 4
Module Description
In this module, you will learn about writing programs in R with the basics of
functions and control structures such as for loop, while and the if functions.
The R Mackdown documentation is introduced to enable the students create
their own documents based on the skills in the other modules of this course.
Further, the module provides videos, examples and quiz for self-assessment in
the learning process.
[1] This module introduces writing programs using R and R Mackdown for
documentation.
Module Learning Outcomes 1
• Show how to write simple programs using R
• Develop a code to generate the fibonacci numbers
• Explain the key sections in r Mackdown document
• Design R Mackdown document
Learning Activities
1. Read the lecture notes (PDF)
2. Read the assigned reference materials
3. Watch lecture videos
4. Complete the module assessment/Quiz
0.1 Computer programs in R
Writing computer programs in R involves creating scripts and functions to per-
form tasks, automate workflows, and analyze data. Writing computer programs
in R requires understanding its syntax, data structures, and control flow mecha-
nisms. By mastering these elements, you can effectively analyze data, automate
tasks, and create reproducible research workflows.
1
0.1.1 Control structures in R
Control structures in R allow you to control the flow of execution of your code.
The main control structures in R include:
1. Conditional Statements: if, else if, else
2. Looping Statements: for, while
3. Vectorized Operations: ifelse, switch
4. Break and Next: break, next
Conditional statements
Conditional statements are used to perform different actions based on different
conditions. The syntax is given as:
if (condition) {
# Code to execute if condition is TRUE
} else if (another_condition) {
# Code to execute if another_condition is TRUE
} else {
# Code to execute if all conditions are FALSE
}
Example 1. x <- 5
if (x > 0) {
print("x is positive")
} else if (x < 0) {
print("x is negative")
} else {
print("x is zero")
}
0.1.2 Practical session
Create a code run for the students to practice the above R codes.
Looping statements
Looping statements are used to repeat a block of code multiple times. The
syntax is given as:
2
For
The syntax is given as:
for (variable in sequence) {
# Code to execute in each iteration
}
Example 2. for (i in 1:5) {
print(i)
}
while loop
The syntax is given as:
while (condition) {
# Code to execute while condition is TRUE
}
Example 3. count <- 1
while (count <= 5) {
print(count)
count <- count + 1
}
0.1.3 Practical session
Create a code run for the students to practice the above R codes.
Vectorized operations
Vectorized operations are used to perform operations on entire vectors without
the need for explicit loops.
Ifelse function
The syntax is given as
ifelse(test, yes, no)
Example 4. x <- c(5, -2, 0, 8, -3)
result <- ifelse(x > 0, "positive", "non-positive")
print(result)
0.1.4 Practical session
Create a code run for the students to practice the above R codes.
3
Switch function
The syntax is given as:
switch(expression, case1, case2, ...)
Example 5. choice <- 2
result <- switch(choice,
"Case 1",
"Case 2",
"Case 3"
)
print(result)
Break and Next
Break statement
Exits the loop immediately.
Example 6. for (i in 1:10) {
if (i == 6) {
break
}
print(i)
}
Next statement
Skips the current iteration and moves to the next iteration.
Example 7. for (i in 1:10) {
if (i %% 2 == 0) {
next
}
print(i)
}
0.1.5 Practical session
Create a code run for the students to practice the above R codes.
0.1.6 Bootstrapping example
Example 8. set.seed(123)
data <- rnorm(50) # Example dataset
bootstrap_means <- numeric(1000)
4
for (i in 1:1000) {
sample_data <- sample(data, replace = TRUE)
bootstrap_means[i] <- mean(sample_data)
}
0.1.7 Practical session
Create a code run for the students to practice the above R codes.
0.1.8 Monte Carlo simulation example
Example 9. set.seed(123)
n <- 10000
inside_circle <- 0
for (i in 1:n) {
x <- runif(1) # Random x coordinate
y <- runif(1) # Random y coordinate
if (x^2 + y^2 <= 1) {
inside_circle <- inside_circle + 1
}
}
pi_estimate <- (inside_circle / n) * 4
0.1.9 Practical session
Create a code run for the students to practice the above R codes.
5
0.1.10 Watch video and attempt the quiz
Video Visit the URL below to view a video:
https://www.youtube.com/embed/si=btTYmlc4UyhA_VwG
Video created by Davis Bundi - R loops and functions
1. (Insert the question after 4:13 minutes). If the 6th term of the
fibonacci is 13, find the 23rd term of the fibonacci. (Answer is
46368) (3 Marks)
2. (Insert after 8:30 minutes). Which of the following code snippets
correctly defines a function named factorial that takes one argu-
ment, n, and returns the factorial of that number? (4 Marks)
(a) Choice A
factorial <- function(n) {
return(n * factorial(n - 1))
}
(b) Choice B (Answer)
factorial <- function(n) {
if (n == 0) return(1)
else return(n * factorial(n - 1))
}
(c) Choice C
factorial <- function(n) {
for (i in 1:n) {
result <- result * i
}
return(result)
}
(d) Choice D
factorial <- function(n) {
return(n + factorial(n - 1))
}
6
0.1.11 Practical session
Create a code run for the students to practice the above R codes.
0.2 R Mackdown
R Markdown is a file format that allows you to create dynamic documents, re-
ports, and presentations that combine text, code, and output from R. It enables
users to write in Markdown—a simple markup language—and embed R code
chunks to perform computations and generate visualizations directly within the
document.
0.2.1 Key features of R Markdown
• Combines Code and narrative: You can write explanatory text alongside
code, making it easier to understand and interpret analyses.
• Dynamic output: Outputs are automatically updated when the code is
run, ensuring that results reflect the most current data and analysis.
• Multiple formats: You can render R Markdown documents to various
formats, including HTML, PDF, and Word.
• Reproducibility: It promotes reproducible research by allowing others to
rerun your analysis with the same code.
0.2.2 Why is R Markdown important
• Integration of code and results: It helps in seamlessly integrating analysis
with reporting, making findings clearer and more accessible.
• Effective communication: R Markdown documents can serve as compre-
hensive reports that communicate results, methodologies, and insights ef-
fectively to a broad audience.
• Automation: R Markdown allows for the automation of report generation,
which is particularly useful for recurring analyses or regular updates.
• Collaboration: Facilitates collaboration among data scientists, statisti-
cians, and stakeholders by providing a clear and understandable format.
0.2.3 How to use R Markdown
1. Installation: Ensure that R and RStudio are installed. R Markdown comes
pre-installed with RStudio, but you can also install the rmarkdown pack-
age if needed.
7
install.packages("rmarkdown")
2. Creating an R Markdown document
• In RStudio, go to File ¿ New File ¿ R Markdown....
• Fill in the title and author information in the dialog box, and choose
the default output format.
3. Writing in R Markdown
• Markdown syntax: Use Markdown syntax for formatting text (head-
ings, lists, links, etc.).
• Code chunks: Embed R code using three backticks and r to indicate
the start of a code chunk.
‘‘‘{r}
summary(mtcars)
‘‘‘
4. Rendering the document
• Click the Knit button in RStudio to render the document to the
chosen format (HTML, PDF, Word).
• You can also render the document programmatically:
rmarkdown::render("your_file.Rmd")
5. Customization
• You can customize the output with YAML metadata at the top of the
R Markdown file, including options for title, author, output format,
and more.
---
title: "My Analysis Report"
author: "Your Name"
output: html_document
---
0.2.4 Watch the video
Watch the following video and create your own R Mackdown document
Click to watch the video
Video by Jenna Tichnon - Basics of creating an R Mackdown file
8
0.2.5 Quiz
Attempt the questions
1. What is the default output format when knitting an R Markdown docu-
ment in RStudio? (2 Marks)
• A) PDF
• B) Word
• C) HTML (Answer)
• D) LaTeX
2. True or False: R Markdown allows you to combine R code and narrative
text in the same document. (Answer is True) (1 Mark)
3. Match the following components of R Markdown with their descriptions
(4 Marks)
(a) YAML header (Answer C)
(b) Code chunk (Answer B)
(c) Markdown (Answer A)
(d) Knit button (Answer D)
• A) Used to format text in the document.
• B) Executes R code and displays results.
• C) Contains metadata about the document.
• D) Initiates the rendering of the document.
4. If you have an R Markdown file with 10 code chunks and you run the
document, how many results will you see in the output if each code chunk
generates one result? (Answer is 10 results) (1 Mark)
5. Which of the following is NOT a valid way to embed R code in an R
Markdown document? (2 Marks)
• A) ‘‘‘r ... ‘‘‘
• B)
r
...
r
• C) \begin{r} ... \end{r} (Answer)
• D) ‘r ...‘
9
0.3 Reading Materials
1. Douglas, A., Roos, D., Mancino, F., Couto, A., and Lusseau, D. (2024).
An introduction to R. eBook (Pages 255-266; 275-300) Read the selected
pages
0.4 Summary
0.4.1 Writing programs in R
R is a powerful programming language widely used for statistical analysis and
data visualization. Writing programs in R involves several fundamental concepts
that help structure code efficiently and effectively. This summary captures key
elements such as control structures and functions.
1. Control structures dictate the flow of execution in R programs. The main
types include:
Conditional Statements
• if: Executes a block of code if a condition is true.
• else if: Specifies a new condition if the previous condition was false.
• else: Executes a block of code if all previous conditions were false.
Loops
• for loop: Iterates over a sequence or vector.
• while loop: Repeats a block of code as long as a condition is true.
• Repeat loop: Repeats indefinitely until a break statement is encoun-
tered.
2. Functions are essential for creating reusable code. They allow you to
encapsulate logic and perform specific tasks.
Defining functions
Use the function() keyword to create a function.
Calling functions
Execute the function by providing the required arguments.
10
Default arguments
Functions can have default values for parameters.
Returning values
Use the return() function to specify what the function should output.
3. R Markdown is a file format used in R for creating dynamic and repro-
ducible documents that combine code, output, and narrative text. It
allows users to generate reports, presentations, and dashboards directly
from R, facilitating the integration of analysis with documentation.
Key features
• Combination of code and text: R Markdown allows you to write
descriptive text using Markdown syntax while embedding R code
chunks to perform calculations and generate visualizations.
• Dynamic documents: The output is automatically updated when the
code is executed, ensuring results are current and accurate.
• Multiple output formats: R Markdown can produce various formats,
including HTML, PDF, Word, and presentations, making it versatile
for different audiences and purposes.
• Reproducibility: By embedding code with data analysis, R Mark-
down promotes reproducible research, enabling others to replicate
results easily.
Basic Structure
An R Markdown document consists of three main parts:
(a) YAML header: Contains metadata such as the title, author, and
output format.
---
title: "My Analysis Report"
author: "Your Name"
output: html_document
---
(b) Markdown text: Utilizes Markdown syntax for formatting text (head-
ings, lists, links).
• Use # for headings, for bullet points, and **bold** for emphasis.
(c) R code chunks: Enclosed in triple backticks with r to run R code and
display results.
11
‘‘‘{r}
summary(mtcars)
‘‘‘
How to use R Markdown
(a) Installation: R Markdown is included in RStudio, but you can install
the rmarkdown package if needed.
install.packages("rmarkdown")
(b) Creating an R markdown file: In RStudio, create a new R Markdown
file via File ¿ New File ¿ R Markdown....
(c) Knit the document: Use the Knit button in RStudio to render the
document into the desired output format.
(d) Customization: Modify the YAML header for different output set-
tings or styles.
Benefits of using R Markdown
• Improved communication: Combines narrative and analysis, making
it easier to present findings.
• Automated reporting: Ideal for generating regular reports or updates
automatically.
• Collaboration: Facilitates collaboration among researchers and stake-
holders by providing clear documentation.
12