13

我在 R 中运行了以下命令并收到了相同的输出matrix()as.matrix()现在我不确定它们之间的区别是什么:

> a=c(1,2,3,4)
> a
[1] 1 2 3 4
> matrix(a)
     [,1]
[1,]    1
[2,]    2
[3,]    3
[4,]    4
> as.matrix(a)
     [,1]
[1,]    1
[2,]    2
[3,]    3
[4,]    4
4

3 回答 3

16

matrix接受data和进一步的论点nrowncol

?matrix
 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.

as.matrix是一种针对不同类型具有不同行为的方法,但主要是从一个 n*m 输入中返回一个 n*m 矩阵。

?as.matrix
 ‘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.

它们之间的区别主要来自输入matrix的形状,不关心形状,as.matrix会维护它(尽管细节取决于输入的实际方法,在您的情况下,无量纲向量对应于单个列矩阵。)输入是原始的、逻辑的、整数的、数字的、字符的还是复杂的等都没有关系。

于 2013-06-04T09:58:04.610 回答
7

matrix 从它的第一个参数构造一个具有给定行数和列数的矩阵. 如果提供的对象对于所需的输出来说不够大,matrix将回收其元素:例如,matrix(1:2), nrow=3, ncol=4). 相反,如果对象太大,则多余的元素将被丢弃:例如,matrix(1:20, nrow=3, ncol=4).

as.matrix 其第一个参数转换为矩阵,其维度将从输入中推断出来。

于 2013-06-04T10:13:35.757 回答
2

matrix 根据给定的一组值创建一个矩阵。as.matrix 尝试将其参数转换为矩阵。

此外,matrix()努力使逻辑矩阵保持逻辑,即,确定特殊结构的矩阵,例如对称、三角形或对角矩阵。

as.matrix是一个通用函数。如果只有原子列和任何非(数字/逻辑/复杂)列,则数据帧的方法将返回一个字符矩阵,将as.vector因子和格式应用于其他非字符列。否则,(logical < integer < double < complex)将使用通常的强制层次结构,例如,所有逻辑数据帧将被强制转换为逻辑矩阵,混合逻辑整数将给出整数矩阵等。

as.matrixcall的默认方法as.vector(x),因此例如将因子强制转换为字符向量。

于 2017-10-11T12:25:18.973 回答