我在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发布于 2013-06-04 17:58:05
matrix接受data以及更多参数nrow和ncol。
?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-04 18:13:36
matrix从它的第一个参数构造一个具有给定行数和列数的矩阵。如果提供的对象对于期望的输出不够大,matrix将回收其元素:例如,matrix(1:2), nrow=3, ncol=4)。相反,如果对象太大,那么多余的元素将被删除:例如,matrix(1:20, nrow=3, ncol=4)。
as.matrix将其第一个参数转换为一个矩阵,矩阵的维数将从输入中推断出来。
发布于 2017-10-11 20:25:19
matrix从给定的值集创建矩阵。as.matrix试图将其参数转换为矩阵。
此外,matrix()努力使逻辑矩阵保持逻辑,即,并确定特殊结构的矩阵,例如对称矩阵、三角形矩阵或对角矩阵。
as.matrix是一个泛型函数。如果只有原子列和任何非(数字/逻辑/复数)列,则用于数据帧的方法将返回字符矩阵,将as.vector应用于因子,并将格式应用于其他非字符列。否则,将使用通常的强制层次结构(logical < integer < double < complex),例如,所有逻辑数据帧将被强制为逻辑矩阵,混合逻辑整数将给出整数矩阵,等等。
as.matrix的默认方法调用as.vector(x),因此将因子强制为字符向量。
https://stackoverflow.com/questions/16913071
复制相似问题