我在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
我在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
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
会关心并保留它(虽然具体方法取决于实际输入的细节,在您的情况下,无维度向量对应于单列矩阵)。输入是原始的、逻辑的、整数的、数字的、字符的或复杂的都没有关系。matrix
会从第一个参数开始构建一个矩阵,并指定行数和列数。如果提供的对象大小不足以生成所需的输出,则matrix
将循环使用其元素,例如:matrix(1:2, nrow=3, ncol=4)
。相反,如果对象过大,则超出部分的元素将被舍弃,例如:matrix(1:20, nrow=3, ncol=4)
。as.matrix
会将其第一个参数转换为矩阵,并从输入中推断出其尺寸。matrix从给定的值集合创建矩阵。as.matrix试图将其参数转换为矩阵。
此外,matrix()
努力保持逻辑矩阵的逻辑性,并确定特殊结构的矩阵,如对称、三角形或对角线矩阵。
as.matrix
是一个通用函数。如果数据框只有原子列和任何非数值/逻辑/复杂列,则数据框的方法将返回字符矩阵,将因子应用as.vector
并将其他非字符列格式化。否则,将使用通常的强制转换层次结构(logical < integer < double < complex)
,例如,所有逻辑数据框将被强制转换为逻辑矩阵,混合逻辑-整数将给出整数矩阵等。
as.matrix
的默认方法调用as.vector(x)
,因此将因子强制转换为字符向量等。
DF <- data.frame(a=1:5,b=6:10); as.matrix(DF); matrix(DF)
。 - Rolandmatrix(matrix(1:10,2))
和as.matrix(matrix(1:10,2))
。 - Roland