The vectors that have been discussed previously in this module were one-dimensional, i.e., they consisted of a simple series of elements that you could imagine being organized in a single row or in a single column. Matrices are a multi-dimensional vectors. A two-dimensional matrix might be envisioned as a table with columns and rows, and a three-dimensional matrix might be envisioned as a series of tables stacked on top of one another.

A matrix can be created in a number of ways. For example,

> x <- matrix(c(1,2,3,4,5,6), ncol=2)

> x

     [,1] [,2]

[1,]    1    4

[2,]    2    5

[3,]    3    6

where the parameter ncol is the number of columns in this matrix, and the numbers are entered by default column-wise. There are two indices, row and column. We can use the commands below to extract portions of the matrix:

> x[3,2]

[1] 6

> x[3,]

[1] 3 6

These commands can be used to call the element of 3rd row and 2nd column in matrix x. If we don't specify any element in the index, R will return all the elements.

> p<- matrix(c(1,2,3,4,5,6), nrow=2)

> p

     [,1] [,2] [,3]

[1,]   1   3   5

[2,]   2   4    6

Other commonly used approaches to create matrix are cbind() and rbind(), which are counterparts of the c() function. The cbind() function is used to combine the variables such that its output contains the original variables in columns while rbind() combines the variables such that its output contains the original variables in row.

For example, the following commands will create the same matrix as x.

> cbind(c(1,2,3), c(4:6))

> rbind(c(1,4), c(2,5), c(3,6))

Suppose we have two vectors, x and y, defined as follows.


> x <- c(-3:3)

> y <- c(2, 5, -6, 3, -2, 10, -4)


  1. Create a matrix, say z, composed of x as the first column and y as the second column.
  2. What's the mean of the first row of matrix z?


Logic Statements (TRUE/FALSE) and cbind and rbind Command in R (R Tutorial 1.7) MarinStatsLectures [Contents]

alternative accessible content

Types of DATA

R has data "types," which are sometimes manipulated differently from each other under certain operations.

The data types are:

There is also lists and arrays, but these will not be covered here.

The str() Command

A useful command is the str() command, which tells you what data type is in a given object, as shown in these two examples:

Example 1


> k <-3

> k

[1] 3

> str(k)

  num 3

Example 2


> w <-"Homer"

> w

[1] "Homer"

> str(w)

   chr "Homer"


The video below provides a nice overview of vectors and matrices and the operations that can be performed on them.

Creating Vectors, Matrices, and Other Intro Topics (R Tutorial 1.2) MarinStatsLectures [Contents]


alternative accessible content