By the end of this lesson, students will be able to:
R is a free, open-source programming language and software environment designed specifically for statistical computing and graphics. It combines a full programming language (variables, functions, control flow) with built-in tools for data analysis, modeling, and visualization.
| Field | Typical Use of R |
|---|---|
| Academic research | Statistical modeling, publication-quality graphics, reproducible papers |
| Public health / epidemiology | Disease modeling, outbreak analysis, survey data |
| Finance | Risk modeling, time series forecasting, portfolio analysis |
| Government & NGOs | Census/survey analysis, policy evaluation |
| Biology / bioinformatics | Genomic data analysis (via Bioconductor) |
| Data journalism | Visualizing and reporting on public datasets |
| Business analytics | Dashboards, A/B testing, customer analytics |
| Feature | R | Excel | SPSS | Python |
|---|---|---|---|---|
| Free & open source | Yes | No | No | Yes |
| Reproducible, scriptable workflow | Yes | Limited | Partial | Yes |
| Handles large/complex data | Yes | Limited | Yes | Yes |
| Built for statistics first | Yes (native) | No | Yes | Via libraries |
| Publication-quality graphics | Excellent (ggplot2) | Basic | Basic | Good (via libraries) |
| Learning curve for beginners | Moderate | Low | Low-Moderate | Moderate |
Key idea: R and Python are often complementary rather than competing — many data professionals use both. R has historically had an edge in statistics and visualization; Python is often preferred for general-purpose software engineering and deep learning. This course focuses on R because of its statistical strengths, which map directly onto university coursework in research methods.
RStudio (the company/product is now branded Posit) is an Integrated Development Environment (IDE) for R. R is the engine; RStudio is the dashboard that makes it dramatically easier to write code, view data, manage files, debug, and produce reports — all in one window.
When you open RStudio, you typically see four panes (their exact
position can be customized in
Tools > Global Options > Pane Layout):
.R files) or R Markdown documents (.Rmd
files). Code here is not run until you explicitly execute
it.| Action | Windows/Linux | Mac |
|---|---|---|
| Run current line/selection | Ctrl+Enter |
Cmd+Enter |
| Run entire script | Ctrl+Alt+R |
Cmd+Option+R |
Insert assignment operator <- |
Alt+- |
Option+- |
Insert pipe |> |
Ctrl+Shift+M |
Cmd+Shift+M |
| Comment/uncomment selected lines | Ctrl+Shift+C |
Cmd+Shift+C |
| Clear console | Ctrl+L |
Cmd+L |
| Knit an R Markdown document | Ctrl+Shift+K |
Cmd+Shift+K |
Learning these shortcuts early saves enormous time over a semester of coding.
Help > Check for Updates inside RStudio checks the IDE
itself.Note: In this course we will save our work as R Markdown (
.Rmd) files, which combine text, code, and output in a single document — this is exactly the format needed to publish your work to RPubs, which we cover in depth in Lesson 20.
The console is like a calculator. Try typing these directly:
## [1] "Hello World"
## [1] 4
## [1] 3.333333
## [1] 25
## [1] 9
Just like in mathematics, R follows an order of operations. Parentheses always take priority.
## [1] 14
## [1] 20
## [1] 512
## [1] -4
## [1] 4
Common mistake: Beginners often expect
-2^2to equal4. In R (and in standard mathematical convention), exponentiation binds tighter than unary minus, so the result is-4. Always use parentheses when you’re unsure.
## [1] "Hello, Kayze"
## [1] "You can also just type a quoted string on its own line"
## cat() prints without quotes and without an index number: Hello!
In R, we store values in objects (also called
variables) using the assignment operator <- (preferred)
or =.
## [1] "Aisha"
## [1] 30
## [1] 90
Best Practice: Use
<-for assignment in R scripts. Use=only inside function arguments (covered in Lesson 8). This is the community standard style, and following it makes your code instantly recognizable as idiomatic R.
## [1] "pass_mark" "student_age" "student_name" "temp_value"
.), and underscores
(_)Score and
score are different objectsTRUE,
FALSE, if, function,
for, NULL, NAscore1 <- 88 # valid
total_score <- 200 # valid, "snake_case" - most common R style
Total.Score <- 200 # valid, dot notation - older R style, still common in base R functions
# 1score <- 5 # INVALID - starts with a number, will throw a syntax errorStyle tip: Pick ONE naming convention (usually
snake_case) and stick with it consistently throughout a project. The tidyverse style guide (widely used in industry and this course) recommendssnake_casefor object and function names.
Base R comes with many built-in functions, but its real power comes from packages — collections of functions, data, and documentation written by the R community and distributed mainly through CRAN.
# Install a package (only needs to be done ONCE per computer)
install.packages("ggplot2")
# Load the package (needs to be done EVERY session you want to use it)
library(ggplot2)We use
eval=FALSEabove so the code doesn’t actually try to install anything when this document is knitted — you should runinstall.packages()yourself, once, in your Console, not inside a script that others will re-run repeatedly.
| Source | Install Command | Notes |
|---|---|---|
| CRAN (most common) | install.packages("pkgname") |
The main, vetted repository |
| Bioconductor | BiocManager::install("pkgname") |
Specialized for genomics/bioinformatics |
| GitHub (development versions) | devtools::install_github("user/repo") |
Cutting-edge, sometimes unstable code |
?mean # Opens help documentation for the mean() function
help("sqrt") # Same thing, written differently
??regression # Searches all installed package documentation
vignette("dplyr") # Opens a longer tutorial document ("vignette"), if the package has one
example(mean) # Runs the worked examples straight from the help fileError messages can look intimidating at first, but they almost always point directly at the problem:
## Error: object 'undefined_variable' not found
Breaking this down: Error in mean(undefined_variable)
tells you which call failed;
object 'undefined_variable' not found tells you exactly why
— R never heard of that object, usually because of a typo or because you
forgot to run the line that created it.
?function_name)[r] tag + your
error message)This very document is an R Markdown file. It mixes:
## [1] 2
When you click Knit in RStudio, it runs all the code and produces a polished HTML (or PDF/Word) report — exactly what you will eventually Publish to RPubs. We will cover R Markdown in full depth in Lesson 20.
| Symptom | Likely Cause | Fix |
|---|---|---|
Error: unexpected symbol |
Missing comma, or a typo | Check the line just before the error carefully |
Error: could not find function |
Package not loaded | Run library(packagename) first |
+ appears in the Console and nothing runs |
An unclosed bracket, quote, or parenthesis | Press Esc, check for a missing ),
], }, or " |
object not found |
Typo in a variable name, or ran chunks out of order | Check spelling and capitalization; re-run from the top |
| Code works when run manually but fails when Knitting | Objects left over in your Environment from earlier experiments | Knitting always starts fresh — make sure your script is fully self-contained |
Rather than scattering files across random folders, create a dedicated RStudio Project for each course or assignment:
File > New Project > New Directory > New Project
This automatically:
setwd() calls).zipScenario: You are recording basic information about yourself as a new R student.
my_name <- "Aisha Ali"
my_university <- "Jaamacadda Borama"
my_favorite_number <- 7
my_year_started <- 2024
# Combine and display information
cat("Name:", my_name, "\n")## Name: Aisha Ali
## University: Jaamacadda Borama
## Favorite number: 7
## Started R in: 2024
# A slightly more advanced combination using paste()
summary_sentence <- paste(my_name, "started at", my_university, "in", my_year_started)
summary_sentence## [1] "Aisha Ali started at Jaamacadda Borama in 2024"
Create a new, blank R script
(File > New File > R Script) and, from scratch, write
code that:
cat() to print a short, well-formatted
introduction paragraph using all four objects.(.packages()).student_profile.R inside a new
RStudio Project.This mini-project intentionally combines everything from this lesson into one realistic, self-contained task — the same pattern every later lesson’s mini-project will follow.
(15 + 5) / 4.3 + 4 * 2 ^ 2.my_age and assign it your
age.my_city and assign it the name
of your city (as text, in quotes).cat() to print a sentence that includes both
my_age and my_city."dplyr" (we will use it in later
lessons) and load it with library().?mean to open the help file for the
mean() function. What are its arguments?File > New File > R Markdown) and click
Knit to see what happens.ls() to view your current environment, then use
rm() to remove one object.<- and -> to assign the
value 100 to two different objects.Q1. What is the main difference between R and RStudio?
Q2. Which symbol is the preferred assignment operator in R?
===<-->>Q3. Which pane in RStudio shows your currently loaded variables and datasets?
Q4. What function do you use to load an already-installed package into your current session?
install.packages()library()require.package()load()Q5. What file extension does an R Markdown document use?
.r.doc.Rmd.htmlQ6. What is the result of -2^2 in
R?
4-42Q7. Which repository is the primary, most common source for installing R packages?
<- and must follow
specific naming rules; rm() and ls() help
manage your environment.library().