ISRT • AST 232 • Reference

R Markdown Guide for AST 232 Exams

A take home reference for writing exam and assignment solutions in R Markdown. All exam submissions in this course should be a knitted .pdf or .html generated from an .Rmd source.

Instructor: K.M. Tanvir • Institute of Statistical Research and Training (ISRT), University of Dhaka

Table of Contents

§ 1What is R Markdown

R Markdown is a plain text file (.Rmd) that mixes three things: normal prose written in Markdown, R code inside "chunks" that runs when you knit the file, and math or tables. When you press Knit in RStudio, the file compiles into a polished PDF, HTML, or Word document with your code, its output, and your interpretation all in one place.

Why we use it for exams. Your answer script is only as trustworthy as the code that produced it. R Markdown pairs each computed number with the exact R that produced it. There is no chance of the code and the answer getting out of sync, and no chance of typos in copied numbers.

What a knitted output looks like

You write prose, followed by a code chunk. When knitted, the reader sees:

  1. Your prose, rendered normally.
  2. The R code itself, in a grey box (like the code blocks on this page).
  3. The output of that code (numbers, tables, plots) right underneath.
  4. Your interpretation, back in prose.

§ 2One Time Setup

Everything you need ships with RStudio. Only a small install step is needed the first time.

# In the R console, once per machine
install.packages(c("rmarkdown", "knitr"))

# For PDF output, you also need a LaTeX distribution.
# The lightweight option that just works everywhere:
install.packages("tinytex")
tinytex::install_tinytex()   # run once, takes 5-10 minutes
Create a new .Rmd file: in RStudio, click File → New File → R Markdown..., give it a title and author, choose the output format, and RStudio drops a template .Rmd into the editor. Save it with a descriptive name like ast232_final_2026.Rmd.

§ 3Anatomy of an .Rmd File

Every R Markdown document has three parts, always in this order.

---
title: "AST 232 Final Exam Solutions"
author: "Your Name, Roll 12345"
date: "2026-08-10"
output: pdf_document
---

# Introduction

Prose goes here. Write in **bold** and *italic*
just like in normal Markdown.

## Question 1

The next block is an R code chunk. Everything between the triple
backticks runs when we knit.

```{r q1-anova}
data(iris)
model <- aov(Sepal.Length ~ Species, data = iris)
summary(model)
```

Interpretation of the ANOVA goes here, again in prose.

§ 4The YAML Header

Only three fields matter for exam submissions: title, author, and output.

---
title:  "AST 232 Final Exam Solutions"
author: "K.M. Tanvir, Roll 20221234"
date:   "2026-08-10"
output: pdf_document
---

Any of pdf_document, html_document, or word_document works. If knitting fails on your machine for any reason, submit the raw .Rmd file itself; it will still be graded.

Optional polish. To automatically number sections and show a table of contents:
output:
  pdf_document:
    toc: true
    number_sections: true

§ 5Text Formatting

The body is plain Markdown. Everything below works in every knitted output.

You typeYou get
# Heading 1Largest heading
## Heading 2Section heading (use for each question)
### Heading 3Sub section (part (a), (b), (c))
**bold**bold
*italic*italic
`code`code
[link text](url)hyperlink
- item or * itembullet list
1. itemnumbered list
> quoteblockquote
empty linenew paragraph

§ 6R Code Chunks

A chunk starts with ```{r} and ends with ```, each on its own line. Everything between runs as R code.

```{r q1-solution}
# Compute the sex ratio
M <- 157500
F <- 162500
SR <- M / F * 100
round(SR, 2)
```

When knitted, the reader sees the code (in a grey box), then the output [1] 96.92. If a chunk produces a plot, the plot appears inline.

Insert a chunk quickly. In RStudio press Ctrl + Alt + I on Windows / Linux, or Cmd + Option + I on Mac. The whole fence appears at the cursor.

§ 7Chunk Options Cheat Sheet

Options go inside the curly braces after r, comma separated: ```{r my-chunk, echo=FALSE, message=FALSE}. The most useful ones:

OptionEffectCommon use
echoShow the code in the outputecho = FALSE hides code but keeps the result
evalActually run the codeeval = FALSE shows code without running it
includeShow anything at allinclude = FALSE runs silently, hides both code and output. Great for setup chunks.
messagePrint R's messagesmessage = FALSE to hide "Attaching package" chatter
warningPrint R's warningswarning = FALSE for cleaner output
resultsHow to render resultsresults = 'hide' to run silently, 'asis' for raw HTML/LaTeX output
fig.width, fig.heightPlot size in inchesfig.width = 6, fig.height = 4 for a compact chart
fig.capFigure captionfig.cap = "Rice yield by fertilizer"
fig.alignAlignmentfig.align = 'center'

Global defaults for the whole document

Set once at the top of the document with a setup chunk, then every later chunk inherits the defaults.

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  echo    = TRUE,       # show code by default
  message = FALSE,      # hide package chatter
  warning = FALSE,      # hide warnings from the reader
  fig.width  = 6,
  fig.height = 4,
  fig.align  = "center"
)
```

§ 8Inline R Code

Sometimes you want a single R value in the middle of a sentence. Wrap it in `r ... ` (backtick, r, space, code, backtick).

The mean rice yield was `r `round(mean(rice$yield), 2)` Mg/ha,
with a sample standard deviation of `r `round(sd(rice$yield), 2)`.

When knitted this reads as: "The mean rice yield was 4.78 Mg/ha, with a sample standard deviation of 0.66." No manual copy paste.

Reproducibility win. If the data changes, the numbers in your prose update automatically on the next knit. This is exactly why we grade R Markdown submissions.

§ 9Nice Tables with knitr::kable

Plain R output like an ANOVA table prints as monospaced text, which reads fine but is not publication grade. knitr::kable() renders any data frame as a formatted table.

```{r anova-table}
model <- aov(yield ~ treat, data = rice)
knitr::kable(
  summary(model)[[1]],
  digits  = 3,
  caption = "ANOVA table for the rice fertilizer trial"
)
```
Handy arguments to kable. digits controls rounding, caption adds a numbered caption, col.names renames the columns, align = 'lrrr' sets alignment column by column (l, c, r).

§ 10Plots and Figures

Every base R plot inside a chunk lands in the knitted output automatically. No ggsave or file handling needed.

```{r yield-boxplot, fig.width=6, fig.height=4, fig.cap="Yield by fertilizer"}
boxplot(yield ~ treat, data = rice,
        col = "#dbeafe", border = "#2563eb",
        xlab = "Fertilizer", ylab = "Yield (Mg/ha)")
```

Two things to remember:

§ 11Math Equations

Math uses LaTeX syntax and renders beautifully in every output format. Two flavours:

The Fergany method computes the probability of dying as
$$
_nq_x = 1 - e^{-n \cdot {_nM_x}}
$$
so the survivors column follows from $l_{x+n} = l_x \cdot _np_x$
with $_np_x = 1 - {_nq_x}$.
Common symbols. Greek letters: \alpha, \beta, \tau, \sigma, \mu. Fractions: \frac{a}{b}. Sums: \sum_{i=1}^n x_i. Subscripts: x_i. Superscripts: x^2. Bold vector: \mathbf{x}. Hat: \hat{y}.

§ 12Knitting to PDF, HTML, Word

Once the file is written, press the Knit button in RStudio (or Ctrl/Cmd + Shift + K). RStudio runs every chunk in order, then compiles the output.

output: fieldProducesNotes
pdf_documentPDF via LaTeXRequires tinytex. The standard for exam submissions.
html_documentSelf contained HTML pageBest for lab work and quick previews.
word_documentEditable .docxUseful when a supervisor needs to add comments in Word.
Common gotcha. When knitting, the whole document runs in a fresh R session. If a chunk depends on a variable defined in an earlier chunk, that earlier chunk must be in the file too. Don't rely on things you typed in the console.

§ 13Ready to Paste AST 232 Exam Template

Copy this into a new .Rmd file to start your exam. Change the header, replace the placeholders, and knit.

---
title: "AST 232 Final Exam Solutions"
author: "Your Name, Roll 20221234"
date: "`r format(Sys.Date())`"
output:
  pdf_document:
    toc: true
    number_sections: true
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  echo    = TRUE,
  message = FALSE,
  warning = FALSE,
  fig.width = 6, fig.height = 4, fig.align = "center"
)
```

# Question 1: Fertility measures for a district

## (a) Compute the Total Fertility Rate

```{r q1a}
age_group  <- c("15-19", "20-24", "25-29", "30-34",
                "35-39", "40-44", "45-49")
female_pop <- c(110000, 105000, 100000, 95000,
                85000,  75000,  65000)
births     <- c(8000, 15000, 11000, 7000,
                2200, 600,   100)
ASFR <- births / female_pop * 1000
TFR  <- 5 * sum(ASFR) / 1000
round(TFR, 3)
```

The Total Fertility Rate is `r `round(TFR, 2)` children per woman,
slightly above the replacement level of 2.10.

## (b) Interpretation

Write your interpretation here in normal prose.

# Question 2: Randomized Complete Block Design

## (a) Fit the ANOVA

```{r q2a}
# Type the data, fit the model, print the ANOVA
```

## (b) Tukey HSD

```{r q2b}
# TukeyHSD on the treatment factor
```
Structuring habit. One heading per question, one sub heading per part. One R chunk per computational step. Prose in between. This makes the knitted PDF easy to grade and easy for you to debug.

§ 14Common Issues and Fixes

"object 'x' not found" when knitting

You referred to a variable that was never defined in the file. Something you typed in the console works there but the knit session cannot see it. Put the definition in a chunk.

PDF fails to build with a LaTeX error

If TinyTeX is installed but the build fails, the missing LaTeX package usually installs itself the next time you knit. If the same error repeats, run tinytex::reinstall_tinytex() once.

Plot looks squished or overflows the page

Set fig.width and fig.height on the offending chunk. For a full page landscape figure try fig.width = 8, fig.height = 5.

Every knit prints "Attaching package: dplyr" and other noise

Add message = FALSE and warning = FALSE to your global setup chunk (see Section 7).

Special characters (Bangla, math) render as ????

Save the file as UTF 8 (File → Save with Encoding → UTF 8). For PDF, ensure the LaTeX engine supports the character set; for Bangla text prefer xelatex in the YAML: output: pdf_document: latex_engine: xelatex.

The knit button greys out

Close and reopen the .Rmd file. If the problem persists, save your work, restart RStudio, and try again.

↑ Back to top