matrix
Matrices
matrix
creates a matrix from the given set of values.
as.matrix
attempts to turn its argument into a matrix.
is.matrix
tests if its argument is a (strict) matrix.
Usage
matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
as.matrix(x, ...)
"as.matrix"(x, rownames.force = NA, ...)
is.matrix(x)
Arguments
- data
- an optional data vector (including a list or
expression
vector). Non-atomic classed R objects are coerced byas.vector
and all attributes discarded. - nrow
- the desired number of rows.
- ncol
- the desired number of columns.
- byrow
- logical. If
FALSE
(the default) the matrix is filled by columns, otherwise the matrix is filled by rows. - dimnames
- A
dimnames
attribute for the matrix:NULL
or alist
of length 2 giving the row and column names respectively. An empty list is treated asNULL
, and a list of length one as row names. The list can be named, and the list names will be used as names for the dimensions. - x
- an R object.
- ...
- additional arguments to be passed to or from methods.
- rownames.force
- logical indicating if the resulting matrix
should have character (rather than
NULL
)rownames
. The default,NA
, usesNULL
rownames if the data frame has automatic row.names or for a zero-row data frame.
Details
If one of nrow
or ncol
is not given, an attempt is
made to infer it from the length of data
and the other
parameter. If neither is given, a one-column matrix is returned.
If there are too few elements in data
to fill the matrix,
then the elements in data
are recycled. If data
has
length zero, NA
of an appropriate type is used for atomic
vectors (0
for raw vectors) and NULL
for lists.
is.matrix
returns TRUE
if x
is a vector and has a
"dim"
attribute of length 2) and FALSE
otherwise.
Note that a data.frame
is not a matrix by this
test. The function is generic: you can write methods to handle
specific classes of objects, see InternalMethods.
as.matrix
is a generic function. The method for data frames
will return a character matrix if there is only atomic columns and any
non-(numeric/logical/complex) column, applying as.vector
to factors and format
to other non-character columns.
Otherwise, the usual coercion hierarchy (logical < integer < double <
complex) will be used, e.g., all-logical data frames will be coerced
to a logical matrix, mixed logical-integer will give a integer matrix,
etc.
The default method for as.matrix
calls as.vector(x)
, and
hence e.g. coerces factors to character vectors.
When coercing a vector, it produces a one-column matrix, and promotes the names (if any) of the vector to the rownames of the matrix.
is.matrix
is a primitive function.
The print
method for a matrix gives a rectangular layout with
dimnames or indices. For a list matrix, the entries of length not
one are printed in the form integer,7 indicating the type
and length.
Note
If you just want to convert a vector to a matrix, something like
dim(x) <- c(nx, ny) dimnames(x) <- list(row_names, col_names)will avoid duplicating
x
.
References
Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.
See Also
data.matrix
, which attempts to convert to a numeric
matrix.
A matrix is the special case of a two-dimensional array
.
Examples
library(base)
is.matrix(as.matrix(1:10))
!is.matrix(warpbreaks) # data.frame, NOT matrix!
warpbreaks[1:10,]
as.matrix(warpbreaks[1:10,]) # using as.matrix.data.frame(.) method
## Example of setting row and column names
mdat <- matrix(c(1,2,3, 11,12,13), nrow = 2, ncol = 3, byrow = TRUE,
dimnames = list(c("row1", "row2"),
c("C.1", "C.2", "C.3")))
mdat
Community examples
``` ma <- matrix( month.abb[c(12, 1:11)], nrow = 3, dimnames = list( c("start", "middle", "end"), c("Winter", "Spring", "Summer", "Fall") ) ) ma[, "Winter"] # to access the data by column name ```
Example files for [LinkedIn Learning: R for Data Science, lunchbreak Learning](https://linkedin-learning.pxf.io/rweekly_matrix) ```r # matrix is a vector or list with 2 dimensions # (Matrix is a 2-dimension Array. Array is like stacked matrices) I.am.a.vector <- c("twas","brillig","and","the","slithey","toves") I.am.a.matrix <- matrix(I.am.a.vector,nrow=2,ncol=3) I.am.a.matrix I.am.a.matrix[2,3] dim(I.am.a.matrix) # byrow I.am.a.matrix <- matrix(I.am.a.vector,nrow=2,ncol=3,byrow=TRUE) I.am.a.matrix I.am.a.matrix <- matrix(I.am.a.vector,nrow=2,ncol=3,byrow=FALSE) I.am.a.matrix # dimnames lots.o.letters <- c(letters[1:10],LETTERS[1:10]) letter.matrix <- matrix(lots.o.letters,ncol = 2,dimnames = list(c(),c("lowercase","UPPERCASE"))) letter.matrix # or by row letter.matrix <- matrix(lots.o.letters,nrow = 2,dimnames = list(c("lowercase","UPPERCASE"),c())) letter.matrix #transpose matrix.transposed <- t(I.am.a.matrix) matrix.transposed[2,3] #oops matrix.transposed[3,2] #works because there are now 3 rows and 2 columns ```
 ## Basic usage Create a matrix by passing an atomic vector, and the number of rows and columns. ```{r} matrix(month.abb, nrow = 3, ncol = 4) ``` Actually, you don't need to specify both the number of rows *and* the number of columns. You can specify one, and `matrix()` will automatically guess the other using the length of the vector. ```{r} matrix(month.abb, nrow = 3) matrix(month.abb, ncol = 4) ``` ## `byrow` argument The elements are added the matrix one column at a time. You can change it so they are added one column at a time using `byrow = TRUE`. For comparison, see the transpose function, [`t()`](https://www.rdocumentation.org/packages/base/topics/t). ```{r} matrix(month.abb, nrow = 4, byrow = TRUE) t(matrix(month.abb, nrow = 3)) ``` ## `dimnames` argument In the same way that a vector can have named elements, a matrix can have row and column names. `dimnames` must be specified as a `list` containing two `character` vectors. The first character vector contains the row names, and the second contains the column names. ```{r} matrix( month.abb[c(12, 1:11)], nrow = 3, dimnames = list( c("start", "middle", "end"), c("Winter", "Spring", "Summer", "Fall") ) ) ``` You can also give names to the dimensions by making `dimnames` a named list. ```{r} matrix( month.abb[c(12, 1:11)], nrow = 3, dimnames = list( position = c("start", "middle", "end"), season = c("Winter", "Spring", "Summer", "Fall") ) ) ``` ## List matrices As well as atomic vectors, you can create a matrix from a `list`. In this case, each element of the matrix is a list. ```{r} prime_seqs <- list( 2, 3, 4:5, 6:7, 8:11, 12:13, 14:17, 18:19, 20:23 ) (prime_matrix <- matrix(prime_seqs, nrow = 3)) prime_matrix[3, 2] ```