Tutorial 1
Installing R
First, you need to download and install the latest version of R.
- Go to R official website
- Click on “download R”
- Save the installation file
- Run the installation file and follow the prompts to install R (default settings are fine)
Installing RStudio
- Go to RStudio
- Click the big blue download button to download the installation file
- Run the installation file and follow the prompts to install RStudio (default settings are fine)
Cheatsheets
If you forget how to use it or are not sure, there are some cheatsheets for you: RStudio cheatsheet
Question set 1 – Getting started
- Q1: Create a new R script
tutorial1.R - Q2: Execute the following code
- Q3: Use RStudio tab panes to explore
fakedata - Q4: Explain the functions
mean()andsd()
Calculate mean and sd for a numeric vector. mean() is the average; sd() is the standard deviation.
- Q5: If we calculate
mean(fakedata), it will result in an error. Why does this happen, and how should we fix the error?
fakedata is a character vector because "5" forces type conversion. Coerce to numeric first:
Question set 2 – Data types
- Q1: We have 25 students in BIOF1001, to store the final marks (0 to 100 with a precision of 0.1), what data type will we use?
Numeric (double).
- Q2: For the grades (
A+toF), what data type and data structure can be used to keep the data?
character and factor.
- Q3: If you have two vectors for the BIOF1001
marksandgradesand onecharacterfor teaching performance"good", and you want to store them into one variable, which data structure will you use?
A list.
Question set 3 – Matrix manipulation
- Q1: Make a matrix named
my_matrixwith a shape of 5 rows and 2 columns, filled with values from 3 to 12, where the first row contains 3 and 4. Hint: For creating a vector from 3 to 12, you may useseq()or:.
- Q2: Based on
Q1, add the row names toDay1toDay5and column names toLunchandDinner.
- Q3: Based on
Q2, extract a matrix with a shape of 3x1 containing the values 6, 8, and 10 from the matrixmy_matrix.
Any of the following:
- Q4: What will you get for
my_matrix[c(TRUE, FALSE, FALSE, TRUE), ]? Hint: think of recycling if the index length is different from the query dimension (Over-flexibility comes with a price of wrong use).
The logical index is recycled to 5 rows, so you get rows 1, 4, and 5 (length 3).
Question set 4 – Analyzing data
- Q1: Now, in your Desktop folder, create a subfolder named
R_exercisesand download this file of differentially expressed genes results Diff_Expression_results.tsv (or link to view) to the folder. Check your current working directory bygetwd()function and change the working directory to the folder you just created. Hint: you may usesetwd()to change the working directory or use theSessionbutton of RStudio.
In RStudio (not WebR): getwd() then setwd("~/Desktop/R_exercises"), or use Session → Set Working Directory.
- Q2: Related to Q1, use the
read.table()function to load the file into a data frame with the variable namedf_DEG. Hint: You may consider using the full path or just the file name if it’s in the same working directory. Please keepheader=TRUEfor the argument. Think how to find the help page for a certain function.
- Q3: Can you calculate the
meanandstandard deviationof thelog2FoldChange?
Question set 5 – Scientific computing
- Q1: Write a function to solve a quadratic equation
\[ ax^2+bx+c=0 \]
Using only material covered so far (warns when the discriminant is negative):
With flow control (later lecture): return NaN when b^2 - 4*a*c < 0.
Lab Overview
You have been hired to audit the sales records of the Downtown Pop-Up Market, which sold Snacks, Drinks, Merch, and Stickers over a three-day weekend.
Work through each chapter by running the code examples and answering the technical questions. Answer keys and code solutions are tucked inside hidden instructor blocks.
1 Vector Arithmetic & Runtime Rules
Before opening, the store established standard retail prices: - Snacks: $12 - Drinks: $5 - Merch: $35 - Stickers: $4
Scalar Broadcasting vs. Vector Operations
Run the following code to inspect how R handles scalar multiplication vs. element-by-element vector arithmetic:
- Calculate the price for each product after including 12.5% if sales tax, and stored in
taxed_prices
- Calculate the price for each product after including the discount rate (in
discount_rates) based on the base price, and stored intdiscounted_prices
Now we will create a dataframe with
Questions to Answer:
What does R do under the hood when multiplying a vector of length 4 by a single number (1 + tax_rate) of length 1?
If you scrambled the order of names in discount_rates to c(Stickers = 0.20, Merch = 0.15, Drinks = 0.00, Snacks = 0.05), does R align calculations by vector names or by index position (1st with 1st, 2nd with 2nd)?
Answer Key
Scalar Broadcasting: In R, there are no true scalar values; 1 + tax_rate is simply an atomic vector of length 1. Through R’s recycling rule, the single value is stretched (recycled) to match the length of base_prices (length 4) so that pairwise multiplication can execute.
Positional Indexing: Standard binary arithmetic operators (+, -, *, /) in R completely ignore names. They match strictly by numeric position (index 1 with index 1, index 2 with index 2). If discount_rates is reordered without realigning base_prices, R will apply the wrong discount to the wrong item. To calculate by name safely, you would need to align them explicitly: discount_rates[names(base_prices)].
Indexing
Please get the Sale_Price column. (Hint: There are few approaches of doing that try to include as much as possibile)
if I would like to get the cell at 3,3 I can use:
Questions to Answer:
- Compare reading price_df[3, 3] versus price_df[“Merch”, “Sale_Price”]. Which one is easier for other readers to understand without looking at the dataset?
- Imagine next month the store adds a new column SKU_Number as the first column (column 1), shifting all other columns to the right. What happens to code written as price_df[, 3] versus code written as price_df[, “Sale_Price”]? Which one is less sensitve to the change?
- Compare the output and
class()ofprice_df$Sale_Priceversusprice_df["Sale_Price"], andprice_df[["Sale_Price"]]Why does single bracket [ ] without a comma return a 1-column data frame, while others extract a raw numeric vector?
Answer Key
- price_df[“Merch”, “Sale_Price”]
- It will refers to
Discountin the new dataset. Soprice_df[, "Sale_Price"]is a better choice as no matter how many column you add the code still works - Slicing with single brackets and no comma (
price_df["Sale_Price"]orprice_df[3])subsets the list container itself, returning a 1-columndata.frame.
Broadcasting rule and warning handeling
Now the market tests a packaging fee on the catalog. Run this chunk and inspect the output:
Questions to Answer:
What does R do under the hood when multiplying a vector of length 4 by a single number (1 + tax_rate) of length 1?
If you scrambled the order of names in discount_rates to c(Stickers = 0.20, Merch = 0.15, Drinks = 0.00, Snacks = 0.05), does R align calculations by vector names or by index position (1st with 1st, 2nd with 2nd)? :::{.hide}
Answer Key
- The Modulo Divisibility Rule: R recycles the shorter vector until it matches the length of the longer vector. When
length(longer) %% length(shorter) == 0 ($4 \pmod 2 = 0$), R assumes the repetition was intended and runs silently. When \(4 \pmod 3 \ne 0\), R wraps back to the first element (1) to finish the math, but issues a warning: longer object length is not a multiple of shorter object length. - Silent Logical Errors: Because R recycles cleanly whenever lengths divide evenly, passing
c(5, 0)adds $5 to Snacks and Merch, but $0 to Drinks and Stickers. Because it is syntactically valid, R raises no error, creating an undetected accounting bug in downstream calculations.
:::
Finding help through ?
Please inspect the value in taxed_prices and the vlaue round(taxed_prices)
Questions to Answer:
- Does
round(taxed_prices)behave as you expected (hint: look at the value with exactly .5) and try to validate your guess withd different cases - Type
?roundinto your R console and scroll to the Details section.- What international standard does R follow?
- and how does it explain the behaviour of
round(taxed_prices)?
Answer key
- No it rounds up/down depends on the odd/even number
- IEC 60559 / IEEE 754 standard, rounded to the nearest even integer.
Data type and coercion
During peak hours, an employee enters “PROMO” into the register price column instead of entering $0 for a free Drink:
Questions to Answer:
- What is the data type for “PROMO” ?
- What will be the datatype of
register_log[1]now? Is it possible to doregister_log[1]+register_log[3]now? - What is R’s hierarchy of datatype ?
Answer key
- Character
- Character, No
- \[ \text{logical} \longrightarrow \text{integer} \longrightarrow \text{double (numeric)} \longrightarrow \text{character} \]