library(tidyverse)
library(here)Intro to R, Quarto, and VSCode
Get comfortable in VS Code, run R code, and render documents with Quarto.
Slides
Worksheet: build your first R notebook
This is the hands-on half of the session. Over the next hour you will build up one Quarto notebook from an empty file, running code and writing a little prose as you go. By the end you will have a small report you wrote yourself.
Open notebooks/02-intro-to-r.qmd in your Codespace and keep this page open next to it. The notebook already has a heading and an empty code chunk for each step below – you fill them in here.
The whole point of this worksheet is one habit, repeated until it feels normal:
write a chunk → run it → write a sentence about what you saw → render.
How to read this worksheet
Every instruction below is one of four kinds. Each has its own coloured box, so you always know what you are being asked to do. Here is one of each:
Copy the chunk into your notebook and click Run Cell above it. The output appears right under the chunk.
Write the code or the prose yourself. There is an empty chunk waiting for it in your notebook.
Open a terminal, type pi, and ask Pi for help. Read what it gives you before you use it.
Click Preview at the top right of the notebook. Read your work as a webpage, the way someone else would.
When you see one of these four boxes, do that one thing. That is all there is to it.
Part 1 — Run a chunk, write a sentence, render
About 10 minutes. The goal here is just the loop. The code is simple on purpose.
Every notebook starts by loading the packages it needs. You already have a setup chunk at the top of 02-intro-to-r.qmd:
This is the setup chunk at the top of your notebook. Run it first, every time you open the notebook.
Now some arithmetic. R is a calculator before it is anything else.
Put this in the Part 1 chunk and run it. The answers appear inline.
3 + 5 + 10
10 * (5 + 1)
2 ** 10Above the chunk, write one plain sentence in your own words, for example: “R treats ** as ‘to the power of’, so 2 ** 10 is 2 multiplied by itself ten times.” This is the prose half of a notebook – code surrounded by your own explanation.
Add these two lines below the others and run again. They look almost the same.
64 / 2 + 2
64 / (2 + 2)Write a sentence explaining why the two lines give different answers. (Hint: what do the brackets change?)
Click Preview. You should see your sentences and your code and its output, laid out as a clean page. That is the loop. You will do it again four more times.
Part 2 — Read the data and look at it
About 13 minutes. From here on you work with the real workshop dataset: the clinical measurements table (02_visit_clinical_measurements) you saw in the slides. One row is one participant at one visit.
In the Part 2 chunk, read the file into a tibble called table_02, then print it. Type it yourself:
table_02 <- read_csv(here(
"data/instructional_dataset/02_visit_clinical_measurements_UKZN_workshop_2023.csv"))
table_02<- saves the data under the name table_02. After this line, table_02 is the data.
Read the printout. Write a sentence recording how many rows and how many columns it has, and name two columns that look interesting to you.
glimpse() is a friendlier way to see every column at once. Add it and run.
glimpse(table_02)Render again. Notice that a printed tibble and a glimpse() look different in the report – both are useful for getting your bearings in a new dataset.
Part 3 — Pull out columns and summarise them
About 13 minutes. A tibble is a stack of columns. Each column is a vector: a sequence of values, all the same type. You can pull one out and do maths on it.
In the Part 3 chunk, pull out the nugent_score column with $ and run it.
table_02$nugent_scoreThat row of numbers is the vector. The Nugent score runs 0–10; 7 or above suggests bacterial vaginosis.
Now summarise a column with a function. mean() takes a vector and gives back one number. Add this and run:
mean(table_02$crp_blood, na.rm = TRUE)na.rm = TRUE tells mean() to skip missing values. Try removing it and running again – what happens, and why?
Save the result under a name so you can reuse it, then print the name:
crp_mean <- mean(table_02$crp_blood, na.rm = TRUE)
crp_meanWrite a sentence reporting the mean blood CRP and what na.rm = TRUE did.
Render. You now have prose, a vector, a summary, and a saved value in one report.
Part 4 — Build something with Pi
About 14 minutes. Pi is the coding agent from Module 1. It runs in the terminal and can read the files in your project. Here you use it the way you should all week: as a fast helper whose work you always check.
Open a terminal (Terminal → New Terminal), type pi, and ask it something specific, naming the file and the columns:
Read
data/instructional_dataset/02_visit_clinical_measurements_UKZN_workshop_2023.csvand write an R chunk that shows the meannugent_scorefor eacharm.
Paste Pi’s chunk into the Part 4 chunk and run it. Did it work first try? If it errored, read the error, paste it back to Pi, and try its fix.
Push back on the code, even if it ran. Ask:
Explain that chunk to me line by line. Why did you use those functions?
Notice when Pi gives a clear, correct explanation and when it sounds confident but vague.
Write a sentence on two things: did Pi’s output actually answer what you asked, and did the column names it used really exist in the data? (Pi sometimes invents column names – always check.)
Render. Part of the skill is making Pi’s contribution fit cleanly into a report that reads as yours.
Capstone — make it your own
About 14 minutes. No step-by-step this time. Build a short piece of analysis about something in this dataset you are actually curious about. The columns nugent_score, crp_blood, ph, arm, and time_point are all fair game.
In the Capstone chunk, pick one numeric column and compute a few summaries of it – some of min(), max(), median(), mean(), sd(). Run as you go.
Use Pi once to push your analysis a step further. For example: “How many visits have a nugent_score of 7 or higher?” or “Show the mean ph at each time_point.” Run its answer and check it.
Write a short paragraph – three or four sentences – saying what you looked at and what you found. Connect it to the biology where you can (for instance, a Nugent score of 7+ is the bacterial-vaginosis range).
Render one last time. This is your notebook. Read it top to bottom as a report and fix anything that does not flow.
Before you go
Pick one step today that confused you. Ask Pi to explain it, then push back: “why did you use X instead of Y?” Notice when Pi sounds confident versus when it is guessing. Using Pi as a study partner rather than an answer machine is the habit that will keep you learning all week.
You do not need to read this to finish the worksheet. It is here for reference when you want a reminder.
Arithmetic
+ - * / add, subtract, multiply, divide
^ or ** power: 2 ** 3 is 8
x %% y remainder: 5 %% 2 is 1
x %/% y whole-number division: 5 %/% 2 is 2Comparisons (give TRUE or FALSE)
< <= > >= less / greater than (or equal)
== equal to
!= not equal to
x & y x AND y
x | y x OR ySummarising a column
mean(x, na.rm = TRUE) average, skipping missing values
median(x) middle value
sd(x) standard deviation
min(x) max(x) smallest / largest
range(x) min and max together
sum(x) total
length(x) how many valuesLooking at a tibble
table_02 print it
glimpse(table_02) every column, one per line
head(table_02) first few rows
nrow(table_02) number of rows
ncol(table_02) number of columns
names(table_02) the column names
table_02$column_name pull out one column as a vectorGetting help
?mean open the help page for a function
?read_csvYou can also ask Pi to explain a function – then check what it says against the help page.
If you finish early and want more, try any of these in your notebook:
- Make your own small tibble from scratch with
tibble()– a few columns of your own data – and summarise one of them. - Compare a measure between the two arms: is the mean
crp_blooddifferent forplaceboversustreatment? (Ask Pi how to do this withgroup_by()andsummarise(), then check the result.) - Pull out just the baseline visits and summarise
phfor them. How would you describe, in one sentence, what “baseline” means here?