Tutorial 1

Author

Yu Cheng Hsu, BBMS1021 teaching team

Published

September 8, 2026

Installing R

First, you need to download and install the latest version of R.

  1. Go to R official website
  2. Click on “download R”
  3. Save the installation file
  4. Run the installation file and follow the prompts to install R (default settings are fine)

Installing RStudio

  1. Go to RStudio
  2. Click the big blue download button to download the installation file
  3. 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() and sd()
Note

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?
Note

Numeric (double).

  • Q2: For the grades (A+ to F), what data type and data structure can be used to keep the data?
Note

character and factor.

  • Q3: If you have two vectors for the BIOF1001 marks and grades and one character for teaching performance "good", and you want to store them into one variable, which data structure will you use?
Note

A list.

Question set 3 – Matrix manipulation

  • Q1: Make a matrix named my_matrix with 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 use seq() or :.
  • Q2: Based on Q1, add the row names to Day1 to Day5 and column names to Lunch and Dinner.
  • Q3: Based on Q2, extract a matrix with a shape of 3x1 containing the values 6, 8, and 10 from the matrix my_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).
Note

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_exercises and download this file of differentially expressed genes results Diff_Expression_results.tsv (or link to view) to the folder. Check your current working directory by getwd() function and change the working directory to the folder you just created. Hint: you may use setwd() to change the working directory or use the Session button 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 name df_DEG. Hint: You may consider using the full path or just the file name if it’s in the same working directory. Please keep header=TRUE for the argument. Think how to find the help page for a certain function.
  • Q3: Can you calculate the mean and standard deviation of the log2FoldChange?

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:

  1. Calculate the price for each product after including 12.5% if sales tax, and stored in taxed_prices
  1. Calculate the price for each product after including the discount rate (in discount_rates) based on the base price, and stored in tdiscounted_prices

Now we will create a dataframe with

Questions to Answer:

  1. What does R do under the hood when multiplying a vector of length 4 by a single number (1 + tax_rate) of length 1?

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

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

  2. 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:

  1. 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?
  2. 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?
  3. Compare the output and class() of price_df$Sale_Price versus price_df["Sale_Price"], and price_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

  1. price_df[“Merch”, “Sale_Price”]
  2. It will refers to Discount in the new dataset. So price_df[, "Sale_Price"] is a better choice as no matter how many column you add the code still works
  3. Slicing with single brackets and no comma (price_df["Sale_Price"] or price_df[3]) subsets the list container itself, returning a 1-column data.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:

  1. What does R do under the hood when multiplying a vector of length 4 by a single number (1 + tax_rate) of length 1?

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

  1. 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.
  2. 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:

  1. 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
  2. Type ?round into 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

  1. No it rounds up/down depends on the odd/even number
  2. 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:

  1. What is the data type for “PROMO” ?
  2. What will be the datatype of register_log[1] now? Is it possible to do register_log[1]+register_log[3] now?
  3. What is R’s hierarchy of datatype ?

Answer key

  1. Character
  2. Character, No
  3. \[ \text{logical} \longrightarrow \text{integer} \longrightarrow \text{double (numeric)} \longrightarrow \text{character} \]