R Tutorial menu

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?

AreaExample
StatisticsTesting if a new medicine works better
Data analysisSummarising survey results from 2,000 students
GraphsBar charts, histograms and maps for reports
ResearchAnalysing data for a university thesis
FinanceStudying share prices and risk

Installing R and RStudio

You need two things:

  1. R itself: download it from the official CRAN website (cran.r-project.org) and install it
  2. 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

PaneWhat 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

r
print("Hello, Karachi!")
Output
[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

r
5 + 3
100 / 8
2^10
Output
[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

r
?mean

Installing a Package

Packages add new functions. Install a package once, then load it in each session with library():

Example

r
install.packages("dplyr")
library(dplyr)

Exercise

Exercise

What does [1] mean at the start of an R result?

Learn R with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp