The matrix()
function can be used to create a matrix of numbers. Before
we use the matrix()
function, we can learn more about it:
?matrix
The help file reveals that the matrix()
function takes a number of inputs,
but for now we focus on the first three: the data (the entries in the matrix),
the number of rows, and the number of columns.
> x = matrix(data = c(1, 2, 3, 4), nrow = 2, ncol = 2)
> x
[,1] [,2]
[1,] 1 3
[2,] 2 4
Note that we could just as well omit typing data=
, nrow=
, and ncol=
in the
matrix()
command above: that is, we could just type
x = matrix(c(1, 2, 3, 4), 2, 2)
and this would have the same effect. However, it can sometimes be useful to specify the names of the arguments passed in, since otherwise R will assume that the function arguments are passed into the function in the same order that is given in the function’s help file.
Note that in the data parameter we pass a vector (with the c()
function).
This vector fills the matrix by column, in this case, this means that the first two elements of the vector are placed in the first column and the second two elements are placed in the second column.
x
with a vector of (7, 8, 5, 3)
as the data parameter.