mat1 <- matrix(1:16,nrow=4)
mat1
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 4 8 12 16
A matrix is a rectangular collection of the same data type (see Figure 8.1). It can be viewed as a collection of column vectors all of the same length and the same type (i.e. numeric, character or logical) OR a collection of row vectors, again all of the same type and length. A data.frame is also a rectangular array. All of the columns must be the same length, but they may be of different types. The rows and columns of a matrix or data frame can be given names. However these are implemented differently in R; many operations will work for one but not both, often a source of confusion.
There are many ways to create a matrix in R. One of the simplest is to use the matrix()
function. In the code below, we’ll create a matrix from a vector from 1:16.
mat1 <- matrix(1:16,nrow=4)
mat1
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 4 8 12 16
The same is possible, but specifying that the matrix be “filled” by row.
mat1 <- matrix(1:16,nrow=4,byrow = TRUE)
mat1
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 5 6 7 8
[3,] 9 10 11 12
[4,] 13 14 15 16
Notice the subtle difference in the order that the numbers go into the matrix.
We can also build a matrix from parts by “binding” vectors together:
x <- 1:10
y <- rnorm(10)
Each of the vectors above is of length 10 and both are “numeric”, so we can make them into a matrix. Using rbind
binds rows (r) into a matrix.
mat <- rbind(x,y)
mat
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
x 1.0000000 2.000000 3.0000000 4.0000000 5.0000000 6.0000000 7.0000000
y -0.2260241 -1.094141 0.1714483 -0.2555133 -0.1925184 -0.7936755 -0.8252991
[,8] [,9] [,10]
x 8.0000000 9.0000000 10.000000
y -0.8556162 0.7268338 -1.243649
The alternative to rbind
is cbind
that binds columns (c) together.
mat <- cbind(x,y)
mat
x y
[1,] 1 -0.2260241
[2,] 2 -1.0941408
[3,] 3 0.1714483
[4,] 4 -0.2555133
[5,] 5 -0.1925184
[6,] 6 -0.7936755
[7,] 7 -0.8252991
[8,] 8 -0.8556162
[9,] 9 0.7268338
[10,] 10 -1.2436490
Inspecting the names associated with rows and columns is often useful, particularly if the names have human meaning.
We can also change the names of the matrix by assigning valid names to the columns or rows.
[1] "apples" "oranges"
mat
apples oranges
[1,] 1 -0.2260241
[2,] 2 -1.0941408
[3,] 3 0.1714483
[4,] 4 -0.2555133
[5,] 5 -0.1925184
[6,] 6 -0.7936755
[7,] 7 -0.8252991
[8,] 8 -0.8556162
[9,] 9 0.7268338
[10,] 10 -1.2436490
Matrices have dimensions.
Indexing for matrices works as for vectors except that we now need to include both the row and column (in that order). We can access elements of a matrix using the square bracket [ indexing method. Elements can be accessed as var[r, c]
. Here, r
and c
are vectors describing the elements of the matrix to select.
The indices in R start with one, meaning that the first element of a vector or the first row/column of a matrix is indexed as one.
This is different from some other programming languages, such as Python, which use zero-based indexing, meaning that the first element of a vector or the first row/column of a matrix is indexed as zero.
It is important to be aware of this difference when working with data in R, especially if you are coming from a programming background that uses zero-based indexing. Using the wrong index can lead to unexpected results or errors in your code.
# The 2nd element of the 1st row of mat
mat[1,2]
oranges
-0.2260241
# The first ROW of mat
mat[1,]
apples oranges
1.0000000 -0.2260241
# The first COLUMN of mat
mat[,1]
[1] 1 2 3 4 5 6 7 8 9 10
# and all elements of mat that are > 4; note no comma
mat[mat>4]
[1] 5 6 7 8 9 10
## [1] 5 6 7 8 9 10
Note that in the last case, there is no “,”, so R treats the matrix as a long vector (length=20). This is convenient, sometimes, but it can also be a source of error, as some code may “work” but be doing something unexpected.
We can also use indexing to exclude a row or column by prefixing the selection with a -
sign.
mat[,-1] # remove first column
[1] -0.2260241 -1.0941408 0.1714483 -0.2555133 -0.1925184 -0.7936755
[7] -0.8252991 -0.8556162 0.7268338 -1.2436490
mat[-c(1:5),] # remove first five rows
apples oranges
[1,] 6 -0.7936755
[2,] 7 -0.8252991
[3,] 8 -0.8556162
[4,] 9 0.7268338
[5,] 10 -1.2436490
We can create a matrix filled with random values drawn from a normal distribution for our work below.
V1 V2
Min. :-1.2254 Min. :-1.4417
1st Qu.:-0.6030 1st Qu.:-1.0352
Median : 0.3881 Median :-0.1091
Mean : 0.2752 Mean : 0.1471
3rd Qu.: 1.1030 3rd Qu.: 0.9386
Max. : 1.6500 Max. : 2.8153
Multiplication and division works similarly to vectors. When multiplying by a vector, for example, the values of the vector are reused. In the simplest case, let’s multiply the matrix by a constant (vector of length 1).
# multiply all values in the matrix by 20
m2 = m*20
summary(m2)
V1 V2
Min. :-24.508 Min. :-28.834
1st Qu.:-12.059 1st Qu.:-20.703
Median : 7.761 Median : -2.181
Mean : 5.505 Mean : 2.943
3rd Qu.: 22.059 3rd Qu.: 18.772
Max. : 33.000 Max. : 56.306
By combining subsetting with assignment, we can make changes to just part of a matrix.
# and add 100 to the first column of m
m2[,1] = m2[,1] + 100
# summarize m
summary(m2)
V1 V2
Min. : 75.49 Min. :-28.834
1st Qu.: 87.94 1st Qu.:-20.703
Median :107.76 Median : -2.181
Mean :105.50 Mean : 2.943
3rd Qu.:122.06 3rd Qu.: 18.772
Max. :133.00 Max. : 56.306
A somewhat common transformation for a matrix is to transpose which changes rows to columns. One might need to do this if an assay output from a lab machine puts samples in rows and genes in columns, for example, while in Bioconductor/R, we often want the samples in columns and the genes in rows.
t(m2)
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 86.90116 113.48913 75.49234 133.00012 108.15383 129.18570 107.368657
[2,] -27.62233 19.16009 56.30615 -14.23669 17.60645 -28.83382 -3.364782
[,8] [,9] [,10]
[1,] 85.4795888 91.05885 124.91609
[2,] -0.9980966 -22.85878 34.26772
Again, we just need a matrix to play with. We’ll use rnorm
again, but with a slight twist.
Since these data are from a normal distribution, we can look at a row (or column) to see what the mean and standard deviation are.
mean(m3[,1])
[1] 5.80262
sd(m3[,1])
[1] 2.140594
# or a row
mean(m3[1,])
[1] 4.987707
sd(m3[1,])
[1] 1.03461
There are some useful convenience functions for computing means and sums of data in all of the columns and rows of matrices.
colMeans(m3)
[1] 5.802620 5.460025 4.821321 4.992476 3.679565 5.079196 4.623018 4.522687
[9] 4.943004 4.878935
rowMeans(m3)
[1] 4.987707 5.146057 5.552158 5.725254 4.228795 5.374928 4.062281 4.421042
[9] 5.316340 3.988285
rowSums(m3)
[1] 49.87707 51.46057 55.52158 57.25254 42.28795 53.74928 40.62281 44.21042
[9] 53.16340 39.88285
colSums(m3)
[1] 58.02620 54.60025 48.21321 49.92476 36.79565 50.79196 46.23018 45.22687
[9] 49.43004 48.78935
We can look at the distribution of column means:
Min. 1st Qu. Median Mean 3rd Qu. Max.
3.680 4.673 4.911 4.880 5.058 5.803
Note that this is centered pretty closely around the selected mean of 5
above.
How about the standard deviation? There is not a colSd
function, but it turns out that we can easily apply functions that take vectors as input, like sd
and “apply” them across either the rows (the first dimension) or columns (the second) dimension.
Min. 1st Qu. Median Mean 3rd Qu. Max.
1.249 1.723 1.985 1.909 2.215 2.327
Again, take a look at the distribution which is centered quite close to the selected standard deviation when we created our matrix.
For this set of exercises, we are going to rely on a dataset that comes with R. It gives the number of sunspots per month from 1749-1983. The dataset comes as a ts
or time series data type which I convert to a matrix using the following code.
Just run the code as is and focus on the rest of the exercises.
data(sunspots)
sunspot_mat <- matrix(as.vector(sunspots),ncol=12,byrow = TRUE)
colnames(sunspot_mat) <- as.character(1:12)
rownames(sunspot_mat) <- as.character(1749:1983)
After the conversion above, what does sunspot_mat
look like? Use functions to find the number of rows, the number of columns, the class, and some basic summary statistics.
Practice subsetting the matrix a bit by selecting:
sunspot_mat[1:10,]
sunspot_mat[,7]
sunspot_mat['1979',7]
These next few exercises take advantage of the fact that calling a univariate statistical function (one that expects a vector) works for matrices by just making a vector of all the values in the matrix. What is the highest (max) number of sunspots recorded in these data?
max(sunspot_mat)
And the minimum?
min(sunspot_mat)
And the overall mean and median?
Use the hist()
function to look at the distribution of all the monthly sunspot data.
hist(sunspot_mat)
Read about the breaks
argument to hist()
to try to increase the number of breaks in the histogram to increase the resolution slightly. Adjust your hist()
and breaks to your liking.
hist(sunspot_mat, breaks=40)
Now, let’s move on to summarizing the data a bit to learn about the pattern of sunspots varies by month or by year. Examine the dataset again. What do the columns represent? And the rows?
# just a quick glimpse of the data will give us a sense
head(sunspot_mat)
We’d like to look at the distribution of sunspots by month. How can we do that?
Assign the month summary above to a variable and summarize it to get a sense of the spread over months.
Play the same game for years to get the per-year mean?
Make a plot of the yearly means. Do you see a pattern?