我跑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
Run Code Online (Sandbox Code Playgroud)
mds*_*ner 14
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.
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)
它们之间的区别主要来自输入matrix的形状,as.matrix不关心形状,是否会保持它(尽管细节取决于输入的实际方法,在您的情况下,无量纲向量对应于单个列矩阵.)输入是原始的,逻辑的,整数的,数字的,字符的还是复杂的等等并不重要.
matrix 从第一个参数构造一个矩阵,具有给定数量的行和列.如果提供的对象不足以满足所需的输出,matrix则会回收其元素:例如,matrix(1:2), nrow=3, ncol=4).相反,如果对象太大,那么剩余元素将被丢弃:例如,matrix(1:20, nrow=3, ncol=4).
as.matrix 将其第一个参数转换为矩阵,其尺寸将从输入中推断出来.