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.
1 2 3 4 5 6 7 8
an optional data vector (including a list or
the desired number of rows.
the desired number of columns.
an R object.
additional arguments to be passed to or from methods.
logical indicating if the resulting matrix
should have character (rather than
If one of
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
NA of an appropriate type is used for atomic
0 for raw vectors) and
NULL for lists.
x is a vector and has a
"dim" attribute of length 2 and
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
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,
The default method for
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.
If you just want to convert a vector to a matrix, something like
will avoid duplicating
Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.
data.matrix, which attempts to convert to a numeric
A matrix is the special case of a two-dimensional
Since R 4.0.0,
inherits(m, "array") is true for a
1 2 3 4 5 6 7 8 9 10
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
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.