1 Learning Objectives

By the end of this lesson, students will be able to:

  • Explain what R and RStudio are, how they relate, and why R is used in modern data-driven fields
  • Describe R’s history and its relationship to the S language
  • Identify the four main panes of the RStudio IDE and use core keyboard shortcuts
  • Install R packages from CRAN and load them into a session
  • Write and run their first lines of R code, understanding operator precedence
  • Understand the basic workflow of an R script and an R Markdown document
  • Read and interpret common beginner error messages
  • Organize a course/project using RStudio Projects

2 What is R?

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.

2.1 A Brief History

  • R was created in the early 1990s by Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand.
  • It is a free, open-source reimplementation of the older S language, developed at Bell Labs in the 1970s by John Chambers and colleagues.
  • Since 1997, R has been maintained by the R Core Team, and the Comprehensive R Archive Network (CRAN) hosts the official releases along with tens of thousands of community-contributed packages.
  • R is released under the GNU General Public License (GPL), meaning it is free to use, study, modify, and redistribute — a major reason for its adoption in academia.

2.2 Why R? Where Is It Actually Used?

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

2.3 R vs. Excel vs. SPSS vs. Python

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.

3 What is RStudio?

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.

3.1 The Four RStudio Panes

When you open RStudio, you typically see four panes (their exact position can be customized in Tools > Global Options > Pane Layout):

  1. Source (top-left): Where you write and edit scripts (.R files) or R Markdown documents (.Rmd files). Code here is not run until you explicitly execute it.
  2. Console (bottom-left): Where code actually runs, one command at a time. You can type directly here for quick, throwaway calculations, but anything you want to keep should live in a script.
  3. Environment/History (top-right): The Environment tab shows every variable and dataset currently loaded in memory (their name, type, and a preview of their value). The History tab logs every command you’ve run.
  4. Files/Plots/Packages/Help (bottom-right): A file browser, the plot viewer (shows your most recent graphics), the package manager (install/update/load packages via checkboxes), and the Help viewer (documentation).

3.2 Essential Keyboard Shortcuts

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.

4 Installing R and RStudio

  1. Download and install R from the Comprehensive R Archive Network: https://cran.r-project.org/
  2. Download and install RStudio Desktop (free version) from: https://posit.co/download/rstudio-desktop/
  3. Always install R before RStudio, since RStudio simply provides an interface to an existing R installation — it does not include R itself.
  4. Periodically update both: new R versions are released roughly once a year; RStudio updates more frequently. 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.

5 Your First R Code

The console is like a calculator. Try typing these directly:

# This is a comment - R ignores anything after a '#'
"Hello World"  # Display text
## [1] "Hello World"
2 + 2          # Addition
## [1] 4
10 / 3         # Division
## [1] 3.333333
5 ^ 2          # Exponentiation (5 squared)
## [1] 25
sqrt(81)       # Square root function
## [1] 9

5.1 Operator Precedence

Just like in mathematics, R follows an order of operations. Parentheses always take priority.

2 + 3 * 4        # multiplication happens before addition -> 14
## [1] 14
(2 + 3) * 4      # parentheses override the default order -> 20
## [1] 20
2 ^ 3 ^ 2        # exponentiation is right-to-left in R -> 2^(3^2) = 512
## [1] 512
-2^2             # unary minus has LOWER precedence than ^ -> -(2^2) = -4
## [1] -4
(-2)^2           # explicit parentheses force squaring -4 first -> 4
## [1] 4

Common mistake: Beginners often expect -2^2 to equal 4. 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.

5.2 Printing Text

print("Hello, Kayze")
## [1] "Hello, Kayze"
"You can also just type a quoted string on its own line"
## [1] "You can also just type a quoted string on its own line"
cat("cat() prints without quotes and without an index number:", "Hello!\n")
## cat() prints without quotes and without an index number: Hello!

6 Assigning Values to Objects

In R, we store values in objects (also called variables) using the assignment operator <- (preferred) or =.

student_name <- "Aisha"
student_age <- 30
pass_mark <- 90

student_name
## [1] "Aisha"
student_age
## [1] 30
pass_mark
## [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.

6.1 Removing Objects and Cleaning Your Environment

temp_value <- 999
ls()                  # lists all objects currently in your environment
## [1] "pass_mark"    "student_age"  "student_name" "temp_value"
rm(temp_value)         # removes a single object
# rm(list = ls())      # removes EVERYTHING - use with caution, often at the top of a fresh script

6.2 Right-to-Left Assignment (Less Common, but Valid)

50 -> pass_mark_alt   # equivalent to pass_mark_alt <- 50
pass_mark_alt
## [1] 50

7 Naming Rules for Objects

  • Must start with a letter (not a number or symbol)
  • Can contain letters, numbers, dots (.), and underscores (_)
  • Are case-sensitive: Score and score are different objects
  • Cannot use reserved words like TRUE, FALSE, if, function, for, NULL, NA
score1 <- 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 error

Style 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) recommends snake_case for object and function names.

8 Working with Packages — A Deeper Look

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.

8.1 Installing and Loading

# 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=FALSE above so the code doesn’t actually try to install anything when this document is knitted — you should run install.packages() yourself, once, in your Console, not inside a script that others will re-run repeatedly.

8.2 Checking What’s Installed and Loaded

installed.packages()[, "Package"]   # lists every installed package (long output!)
(.packages())                         # lists packages currently LOADED in this session
packageVersion("ggplot2")             # check the installed version of a specific package
update.packages()                     # updates all installed packages to their latest version

8.3 Where Packages Come From

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

9 Getting Help in R

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

9.1 Reading an Error Message

Error messages can look intimidating at first, but they almost always point directly at the problem:

mean(undefined_variable)
## 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.

9.2 Good Places to Search for Help

  • The official documentation (?function_name)
  • Stack Overflow (search [r] tag + your error message)
  • RStudio Community forums
  • Package cheatsheets at https://posit.co/resources/cheatsheets/
  • Your course instructor and classmates — reading someone else’s working code is one of the fastest ways to learn

10 R Markdown Basics (Preview)

This very document is an R Markdown file. It mixes:

  • Plain text (like this) written in a simple format called Markdown
  • Code chunks, which look like this:
1 + 1
## [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.

11 Common Beginner Mistakes

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

12 Organizing Your Work with RStudio Projects

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:

  • Sets your working directory to the project folder (no more fragile setwd() calls)
  • Keeps all your scripts, data, and outputs organized together
  • Remembers your open files and settings between sessions
  • Makes your work trivially easy to share as a single folder or .zip

13 Worked Example

Scenario: 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
cat("University:", my_university, "\n")
## University: Jaamacadda Borama
cat("Favorite number:", my_favorite_number, "\n")
## Favorite number: 7
cat("Started R in:", my_year_started, "\n")
## 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"

14 Mini-Project: Build a “Student Profile” Script

Create a new, blank R script (File > New File > R Script) and, from scratch, write code that:

  1. Stores your name, age, major, and favorite subject in four separate objects.
  2. Uses cat() to print a short, well-formatted introduction paragraph using all four objects.
  3. Calculates how many years remain until you turn 30 (or any age of your choosing) using simple arithmetic.
  4. Installs and loads any ONE package of your choice, then confirms it loaded correctly using (.packages()).
  5. Adds at least 3 comments explaining what each section of your script does.
  6. Saves the script as 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 Practice Exercises

  1. Open RStudio and identify all four panes on your screen. Take a screenshot and label each one.
  2. In the Console, calculate the result of (15 + 5) / 4.
  3. Predict, then verify, the result of 3 + 4 * 2 ^ 2.
  4. Create an object called my_age and assign it your age.
  5. Create an object called my_city and assign it the name of your city (as text, in quotes).
  6. Use cat() to print a sentence that includes both my_age and my_city.
  7. Install the package "dplyr" (we will use it in later lessons) and load it with library().
  8. Use ?mean to open the help file for the mean() function. What are its arguments?
  9. Deliberately create an error (e.g., reference an object that doesn’t exist) and read the error message carefully. What does it tell you?
  10. Create a new R Markdown file in RStudio (File > New File > R Markdown) and click Knit to see what happens.
  11. Use ls() to view your current environment, then use rm() to remove one object.
  12. Try both <- and -> to assign the value 100 to two different objects.
  13. Create a new RStudio Project for this course and move your practice files into it.
  14. Look up one keyboard shortcut from Section 2.2 that you didn’t know before and use it at least 3 times today.

16 Quiz: Lesson 1

Q1. What is the main difference between R and RStudio?

  1. They are exactly the same thing
  2. R is the programming language; RStudio is the IDE (interface) for using R
  3. RStudio is a programming language; R is the IDE
  4. There is no difference

Q2. Which symbol is the preferred assignment operator in R?

  1. =
  2. ==
  3. <-
  4. ->>

Q3. Which pane in RStudio shows your currently loaded variables and datasets?

  1. Source
  2. Console
  3. Environment/History
  4. Files/Plots/Packages/Help

Q4. What function do you use to load an already-installed package into your current session?

  1. install.packages()
  2. library()
  3. require.package()
  4. load()

Q5. What file extension does an R Markdown document use?

  1. .r
  2. .doc
  3. .Rmd
  4. .html

Q6. What is the result of -2^2 in R?

  1. 4
  2. -4
  3. An error
  4. 2

Q7. Which repository is the primary, most common source for installing R packages?

  1. PyPI
  2. npm
  3. CRAN
  4. GitHub only
Click to reveal Answer Key Q1: b | Q2: c | Q3: c | Q4: b | Q5: c | Q6: b | Q7: c |

17 Summary

  • R is a language for statistical computing; RStudio is the IDE that makes R easier to use, and Posit is the company behind it.
  • RStudio has four main panes: Source, Console, Environment/History, and Files/Plots/Packages/Help — each with dedicated keyboard shortcuts worth learning early.
  • Objects are created using <- and must follow specific naming rules; rm() and ls() help manage your environment.
  • Packages extend R’s functionality and must be installed once (mainly from CRAN), then loaded every session with library().
  • Reading error messages carefully, and knowing where to look for help, are core skills from day one.