r中的matrix()和as.matrix()有什么区别?

时间:2013-06-04 08:28:58

标签: r

我在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

3 个答案:

答案 0 :(得分:12)

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会做并保持它(尽管细节取决于实际的方法对于输入,在您的情况下,无量纲向量对应于单个列矩阵。)如果输入是原始,逻辑,整数,数字,字符或复杂等,则无关紧要。

答案 1 :(得分:5)

matrix 从第一个参数构造矩阵,具有给定数量的行和列。如果提供的对象不够大,无法满足所需的输出,matrix将回收其元素:例如,matrix(1:2), nrow=3, ncol=4)。相反,如果对象太大,那么剩余元素将被删除:例如,matrix(1:20, nrow=3, ncol=4)

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

答案 2 :(得分:1)

矩阵根据给定的值集创建矩阵。 as.matrix试图将其参数转换为矩阵。

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

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

as.matrix调用as.vector(x)的默认方法,例如强迫角色向量的因素。