Skip to content
LumenaryAcademy
Foundations 50 min

First steps in R

Where R came from and what it is for, installing it, the console and Rscript, and your first lines of R.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

A language built for data

Most programming languages were designed to build software: operating systems, web servers, games. R was designed for a different job: looking at data and drawing conclusions from it. A biologist comparing two treatments, an economist studying wages across regions, an epidemiologist tracking an outbreak, a sports analyst ranking players: their work is to load a table of numbers, summarise it, plot it, fit a statistical model and report what they found, and R is built so that each of those steps is short.

Here is a taste. R comes with a small data set describing 272 eruptions of the Old Faithful geyser in Yellowstone National Park. In three lines you can summarise how long visitors waited between eruptions, count the long eruptions, and measure how strongly eruption length and waiting time go together. You will see the program and its output later in this lesson. In a general-purpose language each of those steps would need a library, a loop or both; in R they are single function calls, because R treats a whole column of numbers as one value.

That is the first thing to learn about R: it thinks in vectors. The second is that it was made by statisticians for statisticians, so it has the statistical methods built in, from averages to regression models, along with a huge collection of contributed packages for nearly every field of research. This course teaches you the language that makes this possible, so that you can use R as professionals do rather than copying recipes.

History & global context

From S at Bell Labs to R

R's story starts with S, a language for statistics developed at Bell Laboratories from 1976 by John Chambers and colleagues. S was designed for interactive data analysis: you typed an expression, saw the result, and typed the next, instead of writing a whole program and waiting for a batch job. It introduced ideas that R users still rely on every day, such as data frames and model formulas. A commercial version, S-PLUS, was widely used in universities and industry in the 1990s.

At the University of Auckland in New Zealand, Ross Ihaka and Robert Gentleman began writing a new language in the early 1990s, for teaching statistics. It looked very much like S, but underneath it borrowed ideas from the Lisp family, in particular the language Scheme. They called it R, partly after their own first initials and partly as a play on S, and first announced it publicly in 1993. In 1995 they released it as free software under the GNU General Public License, and from 1997 a group of volunteers, the R Core Team, took over its development. Version 1.0.0 was released on 29 February 2000.

Two other pieces made R what it is today. CRAN, the Comprehensive R Archive Network, started in 1997 as a network of servers distributing R and its contributed packages; it now hosts more than 20,000 packages, each checked automatically on several operating systems. And from the 2010s, the company now called Posit (formerly RStudio) built the RStudio editor and sponsored the tidyverse, a family of packages for data science with a consistent style, which you will meet in later lessons.

R keeps evolving. Version 4.0 (2020) changed how text columns are read; version 4.1 (2021) added a native pipe operator, |>, and a short syntax for small functions, \(x). R has a new minor release every spring; the release series current in late 2026 is 4.6. This course's programs were checked with R 4.1 and work unchanged in later versions; where a later version adds something useful, the lesson says so.

IntuitionH

How R thinks

A few ideas explain most of R's design, and most of the surprises it holds for programmers coming from other languages.

  • Everything is a vector. There are no single numbers in R, only vectors of length one. x <- 5 makes a numeric vector holding one element. Arithmetic and most functions work element by element on whole vectors, so you rarely write loops over data.
  • Everything that exists is an object, and everything that happens is a function call. John Chambers has summed up R in roughly these words. Even +, [ and if are functions underneath, and functions are values you can pass around, which makes R a functional language at heart.
  • Missing data is normal. Real data has gaps, so R has a built-in value, NA, meaning "not available", and every function has to decide what to do with it.
  • Statistics are part of the language. Means, medians, distributions, random numbers, tests and models come with every installation, and formulas such as waiting ~ eruptions describe models directly.
  • Interactive first. R is meant to be used in conversation: type, look, adjust. Scripts and reports come later, built from what worked.

R's indexing starts at 1, not 0, as in mathematics and in most statistics software. Its strings use either double or single quotes. And its assignment operator is an arrow, <-, a habit inherited from S. You can also assign with =, and both work at the top level, but the arrow is the convention in nearly all R code and style guides, and = is kept for naming arguments inside function calls.

ComputationC

Installing R and running code

Download R from CRAN: choose your operating system, then the "base" installer for Windows, the package for your Mac's processor, or follow the instructions for your Linux distribution (most have R in their package manager, and CRAN provides up-to-date builds for the common ones). Installing R gives you the language, its standard packages, and two ways to run code:

  • The console (start it by typing R in a terminal, or open the R application) shows a prompt, >. Type an expression, press Enter, and R prints the result. If the expression is incomplete, for example a missing closing bracket, the prompt changes to + until you finish it.
  • Rscript runs a whole file: Rscript analysis.R. Every checked program in this course was run as Rscript --vanilla main.R. The --vanilla flag starts R without reading any personal start-up files and without loading or saving a workspace, so the result depends only on the script, which is exactly what you want for reproducible work.

Most people use an editor with a console built in. RStudio, from Posit, has been the standard R editor for over a decade: a script pane, a console, a pane listing the objects you have created, and panes for plots and help. Positron, Posit's newer editor, offers the same for R and Python together. Visual Studio Code with the R extension and Emacs with ESS are also popular. If you cannot install anything right now, the open-source project webR runs R in a browser tab.

Your first script

r
# A first R script. Lines starting with # are comments.
greeting <- "Hello from R"
print(greeting)

# Arithmetic works as you would expect; ^ is "to the power of".
7 + 3 * 2
(7 + 3) * 2
2^10
17 %/% 5   # integer division
17 %% 5    # remainder

# cat() writes text without the [1] prefix; paste() joins strings.
cups <- 3
price <- 2.5
cat("Three cups of tea cost", cups * price, "dollars\n")
label <- paste("Total:", cups * price)
label
text
[1] "Hello from R"
[1] 13
[1] 20
[1] 1024
[1] 3
[1] 2
Three cups of tea cost 7.5 dollars
[1] "Total: 7.5"

Two things are worth noticing. First, a value on a line by itself, such as 7 + 3 * 2 or label, is printed automatically, both in the console and when Rscript runs a file. That is called auto-printing; inside functions and loops it does not happen, and you call print() explicitly. Second, every printed result starts with [1]. That is not part of the value: it is R telling you the position of the first element shown on that line. Because every value is a vector, R always prints it as one, and long vectors wrap over several lines, each starting with the position of its first element.

cat() is the plain way to write text: it joins its arguments with spaces and writes them exactly, without quotes or [1], and you add the newline "\n" yourself. paste() joins its arguments into a string and returns it, so you can store or pass it on.

Worked examplesH

Calling functions and finding help

Nearly everything you do in R is calling functions. Arguments can be given by position or by name, and named arguments can come in any order. Many functions have optional arguments with defaults, which you only name when you want something different. Experienced R programmers name every argument except the first one or two obvious ones, because seq(0, 1, 0.25) makes a reader stop and think while seq(0, 1, by = 0.25) does not.

r
# Arguments can be given by position or by name.
round(3.14159, 2)
round(3.14159, digits = 2)
seq(from = 0, to = 1, by = 0.25)
seq(10, 1)

# Named arguments make calls readable and let you skip optional ones.
paste("na", "na", "na", sep = "-")
paste0(rep("na", 4), collapse = "")

# Most functions work on whole vectors at once.
sqrt(c(4, 9, 16))
toupper(c("lagos", "lima", "kraków"))
nchar(c("R", "Python", "Kraków"))

# Everything is an object that you can ask about.
x <- c(1.5, 2, 2.5)
class(x)
length(x)
is.function(mean)
text
[1] 3.14
[1] 3.14
[1] 0.00 0.25 0.50 0.75 1.00
 [1] 10  9  8  7  6  5  4  3  2  1
[1] "na-na-na"
[1] "nananana"
[1] 2 3 4
[1] "LAGOS"  "LIMA"   "KRAKÓW"
[1] 1 6 6
[1] "numeric"
[1] 3
[1] TRUE

c() ("combine") builds a vector from its arguments, and functions such as sqrt, toupper and nchar returned one result per element. rep("na", 4) repeated a string four times, and paste0(…, collapse = "") glued the pieces into one string. nchar("Kraków") is 6: R counts characters, not bytes, so accented letters count once.

Help is built in

Every function in R and in every CRAN package has a help page, and reading them is a daily habit of experienced R users:

r
?round                 # the help page for round (same as help("round"))
??"standard deviation" # search all help pages for a phrase
example(paste)         # run the examples at the bottom of paste's help page
vignette()             # list long-form guides that packages provide

A help page lists the function's Usage (its arguments and their defaults), what each argument means, what it returns, related functions under See Also, and runnable Examples. When a function surprises you, the answer is usually in the Details section.

Worked examplesH

A first look at data

R installs with dozens of small data sets for practice, in the datasets package, which is always loaded. faithful is one of them: a data frame, R's table type, with a column for each variable and a row for each eruption. You pick a column with $, as in faithful$waiting.

r
# R comes with dozens of small data sets. faithful records 272 eruptions
# of the Old Faithful geyser: eruption length and waiting time, in minutes.
head(faithful, 3)
nrow(faithful)

# One function call summarises a whole column.
summary(faithful$waiting)

# How many eruptions lasted longer than 3 minutes, and what fraction?
long <- faithful$eruptions > 3
sum(long)
round(mean(long), 3)

# Are longer eruptions followed by longer waits?
round(cor(faithful$eruptions, faithful$waiting), 3)
text
  eruptions waiting
1     3.600      79
2     1.800      54
3     3.333      74
[1] 272
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   43.0    58.0    76.0    70.9    82.0    96.0
[1] 175
[1] 0.643
[1] 0.901

head() showed the first rows, and summary() gave the minimum, quartiles, mean and maximum of the waiting times in one call. Then a small piece of R idiom: faithful$eruptions > 3 compares every eruption with 3 and returns a vector of 272 TRUE and FALSE values. Because TRUE counts as 1 and FALSE as 0 in arithmetic, sum() counts the long eruptions and mean() gives their proportion: 64.3% of eruptions lasted more than three minutes. Finally, a correlation of 0.901 says that eruption length and the following wait are strongly related. In three lines you have the beginning of a real analysis; the rest of this course teaches you why each line works and how to go much further.

Common misconceptionsH

First surprises

Misconception

"x <- 5 and x < -5 are the same." The spaces matter to the reader, and the meaning is completely different: the first assigns 5 to x, the second asks whether x is less than minus five. Style guides recommend spaces around <- and around comparison operators so that the two never look alike.

Misconception

"The first element is at position 0." In R it is at position 1, and x[0] returns an empty vector rather than an error, which can hide mistakes for a while. If you come from Python, C or JavaScript, this will catch you once or twice.

Misconception

"Saving the workspace keeps my work safe." When you quit, R offers to save every object to a file called .RData and to restore it next time. Experienced users say no, and configure their editor never to do it: a workspace full of objects whose origin nobody remembers is the opposite of reproducible. Your script is your work; the objects are just its results, and you should always be able to recreate them by running the script from a fresh session, which is what Rscript --vanilla does.

Misconception

"T and F are the same as TRUE and FALSE." They start out that way, but T and F are ordinary variables that anyone can reassign (T <- 0), while TRUE and FALSE are reserved words. Write them in full.

Exercises

Exercises

1. First steps in R

Warm-upComputational

What does this R script print? Write it exactly as R prints it.

x <- c(2, 4, 6)
x * 10

2. First steps in R

Warm-upComputational

What number does 17 %/% 5 * 2 + 17 %% 5 evaluate to in R?

3. First steps in R

CoreComputational

What does this script print? Write the two lines separated by a single space.

cat("tea", "time", sep = "")
cat("\n")
paste("tea", "time")

4. First steps in R

CoreComputational

Daily rainfall in millimetres is stored in rain. What does this script print? Write the two lines separated by a single space.

rain <- c(3, 0, 12, 7, 0, 25)
sum(rain > 5)
mean(rain > 5)

5. First steps in R

Warm-upHuman

Why does this course run every program with Rscript --vanilla main.R?

Choose one

6. First steps in R

Warm-upHuman

R prints 1:30 as two lines, the second starting with [26]. What does [26] mean?

Choose one

7. First steps in R

CoreHuman

Which line follows the usual R style for assigning the mean of scores, ignoring missing values, to avg?

Choose one

Further reading and resources