ZetCode

Introduction to R

last modified November 19, 2026

R is a programming language and an environment for statistical computing and graphics. It is used to clean data, compute summaries, fit statistical models, and draw charts, and it is the working language of a large part of academic statistics, bioinformatics, and data journalism. This article introduces the language, installs R, and runs the first scripts from the console and from a file.

What is R

Ross Ihaka and Robert Gentleman created R at the University of Auckland in the early 1990s. The language is an implementation of S, a statistical language developed at Bell Laboratories, and the name R comes partly from the initials of its authors and partly from its predecessor. Since 1997 the R project has been part of the GNU project, and the source code is distributed under the GNU General Public License.

R is an interpreted language: there is no separate compilation step, and the interpreter reads a command, evaluates it, and prints the result. It is also dynamically typed, which means that the type belongs to a value rather than to a variable, so the same name can hold a number and later a string. The language is built around vectors, an ordered collection of values of the same type, and most operations work on a whole vector at once instead of one element at a time.

A large part of R's usefulness comes from packages: collections of functions and data that extend the base language. The Comprehensive R Archive Network (CRAN) hosts thousands of them for statistics, machine learning, biology, finance, and graphics. The base installation already contains enough for the articles in this series, and packages are introduced later.

Installing R

R runs on Linux, macOS, and Windows. The official download page at cran.r-project.org lists the installers and the repositories for the common Linux distributions. The table shows the shortest installation path for each system.

SystemInstallation
Debian, Ubuntusudo apt install r-base
Fedorasudo dnf install R
macOSthe .pkg installer from CRAN
Windowsthe .exe installer from CRAN
Dockerdocker run -it --rm r-base

A package from a distribution repository may be older than the current release, but that is rarely a problem for learning the language. When a recent version matters, CRAN publishes its own repositories for Debian and Ubuntu, and the download page explains how to add them. The examples in this article were run with R 4.5.2 from the official r-base Docker image.

The installation provides two commands. R starts the interactive console, and Rscript runs a file without opening a console. Both accept --version, which prints the release, the date, and the platform.

$ R --version
R version 4.5.2 (2025-10-31) -- "[Not] Part in a Rumble"
Copyright (C) 2025 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under the terms of the
GNU General Public License versions 2 or 3.
For more information about these matters see
https://www.gnu.org/licenses/.

The console

Running R in a terminal opens the console, also called a read-eval-print loop (REPL): it reads one command, evaluates it, prints the result, and waits for the next command. The prompt is a greater-than sign. When a command is not finished, for example because a parenthesis is still open, the prompt changes to a plus sign and the console waits for the rest.

A line such as 2 + 3 is an expression, a piece of code that produces a value. The console prints the value with a leading [1], which is the index of the first element of the result. An assignment stores a value under a name and returns the value invisibly, so it prints nothing. Typing q() ends the session.

$ R --quiet --no-save
> 2 + 3
[1] 5
> x <- 10
> x * 2
[1] 20
> q()

The first script

A script is a text file with R commands. The interpreter reads the file from top to bottom, the same way it reads lines from the console. Comments start with a hash sign and run to the end of the line. The first script prints a greeting with cat, a function that writes its arguments to the standard output.

hello.R
# print a greeting
cat("Hello there!\n")

The quoted text is a string, and \n is an escape sequence that stands for a newline; without it, the next output would continue on the same line. The command below runs the script with Rscript. The interpreter starts, executes the file, and exits, so no prompt appears in the output.

$ Rscript hello.R
Hello there!

print and cat

The console prints a value by calling print, and a script can call it directly. print shows strings with quotes and marks the position of each element with an index. cat does neither: it concatenates its arguments, separates them with a space, and writes the result without quotes or indices. The next script shows both functions on the same string.

printcat.R
print("Hello there!")
cat("Hello there!\n")

The [1] before the quoted string is not part of the value; it is the index of the first element on that line, and it appears because a character vector can hold more than one string. cat is the better choice for messages and formatted text, while print is the better choice when the exact structure of a value matters.

$ Rscript printcat.R
[1] "Hello there!"
Hello there!

Variables

An assignment gives a value a name, and the stored value is called an object. In R the usual assignment operator is <-, which points from the value to the name. A variable is a name that refers to an object; the value can be replaced at any time, and the type of the new value does not have to match the old one.

vars.R
name <- "R"
version <- 4.5
cat(name, "version", version, "\n")

The first assignment stores a string and the second stores a number. cat accepts any number of arguments, converts each one to text, and puts a space between them. The [1] index does not appear because cat does not format its arguments as R objects.

$ Rscript vars.R
R version 4.5 

Vectors

A vector is the basic data structure of R: an ordered collection of values of one type. The function c, short for combine, concatenates its arguments into a vector. A function is a named piece of code that performs a task, and the values written inside its parentheses are called arguments. In the next script the vector holds five exam scores, and mean and max compute the average and the largest score.

first-vector.R
scores <- c(72, 85, 90, 66, 78)
cat("scores:", scores, "\n")
cat("mean:", mean(scores), "\n")
cat("highest:", max(scores), "\n")

The vector is created once and then used three times. This is the central habit of R: build a vector, then pass the whole vector to a function instead of writing a loop over its elements. The functions mean and max are vectorised, which means that they accept a vector and return a single summary value.

$ Rscript first-vector.R
scores: 72 85 90 66 78 
mean: 78.2 
highest: 90 

Vectorised arithmetic

Arithmetic is vectorised too. When an operator is applied to a vector and a single number, the number is reused for every element, a rule called recycling. Comparisons work the same way and return a logical vector of TRUE and FALSE values. Because TRUE counts as one and FALSE as zero, sum over a logical vector counts how many comparisons were true.

vectorized.R
scores <- c(72, 85, 90, 66, 78)
curved <- scores + 5
cat("curved:", curved)
cat("\n")
passed <- scores >= 70
cat("passed:", passed)
cat("\n")
cat("count:", sum(passed))
cat("\n")

Adding five to the vector adds five to each element and produces a new vector of the same length. The comparison scores >= 70 produces five logical values, one per score, and their sum is four. No loop is needed, and the original vector is not modified because the result is stored in a new object.

$ Rscript vectorized.R
curved: 77 90 95 71 83
passed: TRUE TRUE TRUE FALSE TRUE
count: 4

Summaries

The function summary prints several statistics of a vector at once: the smallest value, the first quartile, the median, the mean, the third quartile, and the largest value. The median is the middle value when the values are sorted, and a quartile cuts off a quarter of the sorted values. summary also accepts a data frame, a table with one column per variable, and then summarises every column.

summaries.R
scores <- c(72, 85, 90, 66, 78)
print(summary(scores))

The output is a named vector, so every number has a label above it. The mean is 78.2 and the median is 78, which means that the scores are nearly symmetric around the middle. The labels are part of the printed value, not separate text; later articles show how names are attached to a vector.

$ Rscript summaries.R
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   66.0    72.0    78.0    78.2    85.0    90.0 

Installing packages

A package is a bundle of functions, data, and documentation. The base installation ships with a few packages, such as stats and graphics, that are attached at startup, while CRAN, the Comprehensive R Archive Network, hosts thousands of add-on packages. An add-on package is installed once with install.packages, typed at the console or run from the shell:

$ Rscript -e 'install.packages("tibble", repos = "https://cloud.r-project.org")'

Several packages can be installed at once by passing a vector of names, for example install.packages(c("dplyr", "ggplot2")). On Linux, a user without write access to the system library is offered a personal library in the home directory. After installation, a script attaches the package with library. If the package is missing, the call stops with an error such as there is no package called 'tibble'.

first-package.R
library(tibble)
scores <- tibble(name = c("Ada", "Grace", "Alan"), score = c(90, 85, 66))
print(scores)
cat("tibble version:", as.character(packageVersion("tibble")), "\n")

The script attaches the tibble package, builds a small table with its tibble function, and prints the installed version with packageVersion. Base R knows nothing about tibbles; the function and the compact printout come from the package. The packages article covers the namespace operator, checking for and detaching packages, and reporting versions.

$ Rscript first-package.R
# A tibble: 3 × 2
  name  score
  <chr> <dbl>
1 Ada      90
2 Grace    85
3 Alan     66
tibble version: 3.3.1 

Editors and IDEs

R works in any text editor, but an integrated development environment (IDE) adds a console, a script editor, a plot pane, and a help browser in one window. RStudio, now developed by Posit, is the most common choice and is available in a free desktop edition. Positron is a newer IDE from the same company, built on Visual Studio Code, and the R extension for Visual Studio Code turns that editor into a capable R environment. Emacs with ESS and Jupyter with an R kernel are older alternatives that remain in use.

An IDE is convenient but not required. Every example in this series is a plain script that runs with Rscript, so a terminal and a text editor are enough. Keeping the examples in files also makes the output reproducible and easy to compare with the results shown in the articles.

Next steps

The next two articles look at the session around a script. The console and scripts article covers the prompt, Rscript, the working directory, startup files, and command-line arguments, and the help and documentation article shows how to read the page for any function. After that, the variables and assignment article explains how names are chosen, how assignment works as a function call, and how objects are listed and removed. The data types article surveys the six atomic types, and the operators article covers arithmetic, comparison, and logical operators in detail.

Source

The R Project for Statistical Computing

The Comprehensive R Archive Network

An Introduction to R

The R Language Definition

In this article we have introduced the history and the vector-based model of R, installed the interpreter, used the console, and run scripts with Rscript. We printed text with print and cat, stored values in variables, built a vector, applied vectorised arithmetic, summarised the vector with summary, and installed and attached an add-on package. The series continues with the console and scripts and help articles, and then with R variables and assignment.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.