Biostatistics · Introductory

Using R

Written by SignalsLab

Early edition: these lessons are being reviewed.

Content

Summary

R is a free, open-source statistical computing environment where users enter commands at a prompt, typically using GUIs like RStudio. Data is managed through objects and vectors, with arithmetic and statistical operations performed element-wise or via specific functions like mean() and sd().

Intuition

Think of R as a sophisticated calculator that remembers your work. You type instructions at a prompt, and R executes them immediately. Unlike simple calculators, R stores your results in 'objects' (like vectors) which you can manipulate later. A key feature is that operations like addition or square roots happen 'element-wise,' meaning they apply to every number in a list simultaneously. This makes R powerful for handling datasets, but you must remember that functions like var() calculate sample variance by default, and standard procedures may not work for complex tasks like meta-analysis without specific packages.

Key equations

x<−c(1,3,2,5)
(1)

Assignment operator creating a vector named x.

mean(x)
(2)

Function to compute the arithmetic average of vector x.

sd(x)
(3)

Function to compute the standard deviation, assuming sample data.

weighted.mean(values,weights)
(4)

Function to compute an average where each value has a specific importance.

Derivation

  1. R operates by executing commands entered at the prompt (symbol >).
  2. Users create objects using the assignment operator <- or =.
  3. Vectors are created using c() and support element-wise arithmetic.
  4. Statistical summaries are generated using built-in functions like mean(), var(), and sd().
  5. Data import requires handling headers and missing values (NA) correctly.

Worked example

Problem

Calculate the weighted mean price for a portfolio with 200 shares at USD 78, 300 shares at USD 122, and 500 shares at USD 131.

  1. Define the price vector: price <- c(78, 122, 131)
  2. Define the weight vector (shares): shares <- c(200, 300, 500)
  3. Execute: weighted.mean(price, shares)

Answer 117.7

Common mistakes

  • Assuming var() calculates population variance; it calculates sample variance by default.
  • Plotting variables without specifying the dataset (e.g., plot(cylinders, mpg) instead of plot(Auto$cylinders, Auto$mpg)).
  • Ignoring the header argument in read.table(), causing variable names to be treated as data.
  • Applying standard R procedures to meta-analysis data, which yields incorrect p-values due to differing degrees of freedom rules.

Animation

Animation coming soon

The animated version of this lesson is being prepared for the web. In the Signals AI app, lessons are drawn step by step.

Code

This is a text lesson: it has no animation code yet.

ccBYNC© 2026 SignalsLab. Lesson text shared as is under CC BY-NC 4.0.