Skip to Content
R in a Nutshell
book

R in a Nutshell

by Joseph Adler
January 2010
Beginner
634 pages
19h 50m
English
O'Reilly Media, Inc.
Content preview from R in a Nutshell

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 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. Vectors 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,] 1 4 7 10 [2,] ...
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, 2nd Edition

R in a Nutshell, 2nd Edition

Joseph Adler
The Big R-Book

The Big R-Book

Philippe J. S. De Brouwer
R Packages

R Packages

Hadley Wickham

Publisher Resources

ISBN: 9781449377502Supplemental ContentErrata Page