2013-06-04 30 views
9

我跑R中的以下内容并收到了同样的输出都matrix()as.matrix(),现在我不知道它们之间的区别是什么: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

阅读文档。例如,比较DF < - data.frame(a = 1:5,b = 6:10)的输出; as.matrix(DF);矩阵(DF)'。 – Roland

+1

是的,但我没有处理data.frame,即我的矩阵只是数字数据。 –

+2

你问这些功能之间的区别。差异是记录在案,我向你展示了一个例子。功能可以(在特定情况下)给出相同的结果,不会影响您对问题的回答。 – Roland

回答

9

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现在和将来保持它(虽然细节取决于对输入的实际方法,并在您的情况下的无量纲矢量对应于一个列的矩阵。)如果输入是原始的,逻辑的,整数,数字,字符或络合物等

4

matrix构建从其第一矩阵不要紧参数,给定数量的行和列。如果提供的对象对于所需的输出不够大,则matrix将回收其元素:例如matrix(1:2), nrow=3, ncol=4)。相反,如果物体太大,则剩余元素将被丢弃:例如,matrix(1:20, nrow=3, ncol=4)

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

0

矩阵根据给定的一组值创建矩阵。 as.matrix尝试将其参数转换为矩阵。此外,Matrix()还努力使逻辑矩阵保持逻辑,即确定特殊结构的矩阵,如对称矩阵,三角形对角矩阵或对角矩阵。 as.matrix是一个通用函数。如果只有原子列和任何非(数字/逻辑/复合)列,将as.vector应用于因子和格式到其他非字符列,则数据框的方法将返回字符矩阵。否则,通常胁迫层次结构(逻辑<整数<双<配合物)将被使用,例如,所有逻辑数据帧将被强制为逻辑矩阵,混合逻辑整数会给出一个整数矩阵等

as.matrix的默认方法调用as.vector(x),因此例如强制要素向量。

相关问题