在R中,as.data.frame(x)
和data.frame(x)
函数有什么区别?
在下面的示例中,除了列名之外,结果是相同的。
x <- matrix(data=rep(1,9),nrow=3,ncol=3)
> x
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 1 1
[3,] 1 1 1
> data.frame(x)
X1 X2 X3
1 1 1 1
2 1 1 1
3 1 1 1
> as.data.frame(x)
V1 V2 V3
1 1 1 1
2 1 1 1
3 1 1 1
6条答案
按热度按时间4ktjp1zp1#
正如Jaap所提到的,
data.frame()
调用as.data.frame()
,但这是有原因的:as.data.frame()
是一个将其他对象强制到类data.frame
的方法。如果你正在编写你自己的包,你应该将你的方法存储在as.data.frame.your_class()
下,以转换your_class
的对象。这里仅举几个例子。mtb9vblg2#
data.frame()
可用于构建 Dataframe ,而as.data.frame()
仅可用于强制其它对象到 Dataframe 。例如:
zf9nrax13#
正如您所注意到的,结果确实略有不同,这意味着它们并不完全相等:
因此,您可能需要注意在使用哪一个时保持一致。
但值得注意的是,
as.data.frame
更快:p4rjhz4m4#
当你看看他们的主要论点时,差异就变得更明显了:
因此,奥菲利亚的结果是相似的,因为这两个函数都接收一个矩阵作为参数:然而,当这些函数接收2个(或更多)向量时,区别变得更清楚:
如您所见,“data.frame()”工作正常,而“as.data.frame()”会产生错误,因为它将第一个参数识别为要检查和强制的对象。
总而言之,“as.data.frame()”应该用来将一个R对象转换/强制为一个 Dataframe (就像您使用矩阵正确地做的那样),而“data.frame()”则用来从头开始构建一个 Dataframe 。
sqougxex5#
试试看
然后两者都会给予相同的结果
更令人吃惊的是以下情况:
提供一个单元素列表,元素是矩阵x;而
给出了一个包含9个元素的列表,每个矩阵项一个
MM
ego6inou6#
查看代码,
as.data.frame
失败得更快。data.frame
将发出警告,并在存在重复行时执行删除行名等操作: