在R语言中,matrix()和as.matrix()有什么区别?

14

我在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); matrix(DF) - Roland
1
是的,但我没有处理数据框,我的矩阵只包含数值数据。 - Linda Rabady
3
你要求说明这些函数的区别。这个差异已经有文档记录,并且我给你展示了一个示例。在特定情况下,这些函数可能会给出相同的结果,但这并不影响回答你的问题。 - Roland
谢谢您的回复。我实际上已经阅读了文档,从您给出的示例中清楚地看出了它们之间的区别。我认为在我所面对的只有数值数据的情况下,它们之间没有任何区别。 - Linda Rabady
3
不正确。比较 matrix(matrix(1:10,2))as.matrix(matrix(1:10,2)) - Roland
9
@Roland -- 我不认为当有人问一个具体问题时,回答RTFM(读手册吧)很有用。 - abalter
3个回答

17

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 会关心并保留它(虽然具体方法取决于实际输入的细节,在您的情况下,无维度向量对应于单列矩阵)。输入是原始的、逻辑的、整数的、数字的、字符的或复杂的都没有关系。

7
matrix会从第一个参数开始构建一个矩阵,并指定行数和列数。如果提供的对象大小不足以生成所需的输出,则matrix将循环使用其元素,例如:matrix(1:2, nrow=3, ncol=4)。相反,如果对象过大,则超出部分的元素将被舍弃,例如:matrix(1:20, nrow=3, ncol=4)as.matrix会将其第一个参数转换为矩阵,并从输入中推断出其尺寸。

2

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

此外,matrix()努力保持逻辑矩阵的逻辑性,并确定特殊结构的矩阵,如对称、三角形或对角线矩阵。

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

as.matrix的默认方法调用as.vector(x),因此将因子强制转换为字符向量等。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接