Skip to Content
R in a Nutshell, 2nd Edition
book

R in a Nutshell, 2nd Edition

by Joseph Adler
October 2012
Beginner to intermediate
721 pages
21h 38m
English
O'Reilly Media, Inc.
Content preview from R in a Nutshell, 2nd Edition

Other Objects

There are some other objects that you should know about if you’re using R. Although most of these objects are not formally part of the R language, they are used in so many R packages, or get such special treatment in R, that they’re worth a closer look.

Matrices

A matrix is an extension of a vector to two dimensions. A matrix is used to represent two-dimensional data of a single type. A clean way to generate a new matrix is with the matrix function. As an example, let’s create a matrix object with three columns and four rows. We’ll give the rows the names “r1,” “r2,” “r3,” and “r4,” and the columns the names “c1,” “c2,” and “c3.”

> m <- matrix(data=1:12, nrow=4, ncol=3,
+             dimnames=list(c("r1", "r2", "r3", "r4"),
+                           c("c1", "c2", "c3")))
> m
   c1 c2 c3
r1  1  5  9
r2  2  6 10
r3  3  7 11
r4  4  8 12

It is also possible to transform another data structure into a matrix using the as.matrix function.

An important note: matrices are implemented as vectors, not as a vector of vectors (or as a list of vectors). Array subscripts are used for referencing elements and don’t reflect the way the data is stored. (Unlike other classes, matrices don’t have an explicit class attribute. We’ll talk about attributes in Attributes.)

Arrays

An array is an extension of a vector to more than two dimensions. Arrays are used to represent multidimensional data of a single type. As above, you can generate an array with the array function:

> a <- array(data=1:24, dim=c(3, 4, 2))
> a , , 1 [,1] [,2] [,3] [,4] [1,] ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

R in a Nutshell

R in a Nutshell

Joseph Adler
The R Book, 2nd Edition

The R Book, 2nd Edition

Michael J. Crawley
The R Book

The R Book

Michael J. Crawley
R Packages

R Packages

Hadley Wickham

Publisher Resources

ISBN: 9781449358204Errata Page