R Introduction
R is a free programming language built for statistics, data analysis and graphs.
What is R?
- R was created by Ross Ihaka and Robert Gentleman in New Zealand, and first released in 1993
- It is free and open source, and works on Windows, macOS and Linux
- It is an interpreted language: you type a line and see the result straight away
- Its huge collection of add-on packages is stored on a site called CRAN
What is R Used For?
| Area | Example |
|---|---|
| Statistics | Testing if a new medicine works better |
| Data analysis | Summarising survey results from 2,000 students |
| Graphs | Bar charts, histograms and maps for reports |
| Research | Analysing data for a university thesis |
| Finance | Studying share prices and risk |
Installing R and RStudio
You need two things:
- R itself: download it from the official CRAN website (cran.r-project.org) and install it
- RStudio: a free editor that makes R much easier to use. Download "RStudio Desktop" from the Posit website
Install R first, then RStudio. RStudio uses the R you installed. If you cannot install anything, search for an online R editor, or use R in Google Colab by choosing the R runtime.
The RStudio Window
| Pane | What it is for |
|---|---|
| Source (top left) | Writing and saving scripts (.R files) |
| Console (bottom left) | Where code runs and results appear |
| Environment (top right) | Shows the variables you have created |
| Files / Plots / Help (bottom right) | Files, charts and help pages |
Your First R Code
Type this in the console and press Enter:
Example
print("Hello, Karachi!")[1] "Hello, Karachi!"
The [1] at the start is not part of the answer. It means "this is the first value of the result". You will see it often.
You can also use R as a calculator:
Example
5 + 3
100 / 8
2^10[1] 8 [1] 12.5 [1] 1024
In the console, R prints the result of each line automatically, even without print().
Running a Script
For longer code, create a new script in RStudio (File, New File, R Script), type your lines, and save it with the ending .R, for example first.R.
- Press Ctrl + Enter to run the current line
- Press Ctrl + Shift + Enter to run the whole script
Getting Help
Put a question mark in front of a function name to open its help page:
Example
?meanInstalling a Package
Packages add new functions. Install a package once, then load it in each session with library():
Example
install.packages("dplyr")
library(dplyr)Exercise
Exercise
What does [1] mean at the start of an R result?
