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
发布于 2014-02-05 18:43:29
正如Jaap所提到的,data.frame()
调用as.data.frame()
是有原因的:
as.data.frame()
是一种强制其他对象为data.frame
类的方法。如果你正在编写你自己的包,你应该在as.data.frame.your_class()
下存储你的方法来转换your_class
的对象。这里只是几个例子。
methods(as.data.frame)
[1] as.data.frame.AsIs as.data.frame.Date
[3] as.data.frame.POSIXct as.data.frame.POSIXlt
[5] as.data.frame.aovproj* as.data.frame.array
[7] as.data.frame.character as.data.frame.complex
[9] as.data.frame.data.frame as.data.frame.default
[11] as.data.frame.difftime as.data.frame.factor
[13] as.data.frame.ftable* as.data.frame.integer
[15] as.data.frame.list as.data.frame.logLik*
[17] as.data.frame.logical as.data.frame.matrix
[19] as.data.frame.model.matrix as.data.frame.numeric
[21] as.data.frame.numeric_version as.data.frame.ordered
[23] as.data.frame.raw as.data.frame.table
[25] as.data.frame.ts as.data.frame.vector
Non-visible functions are asterisked
发布于 2014-08-25 09:59:32
data.frame()
可用于构建数据帧,而as.data.frame()
只能用于将其他对象强制到数据帧。
例如:
# data.frame()
df1 <- data.frame(matrix(1:12,3,4),1:3)
# as.data.frame()
df2 <- as.data.frame(matrix(1:12,3,4),1:3)
df1
# X1 X2 X3 X4 X1.3
# 1 1 4 7 10 1
# 2 2 5 8 11 2
# 3 3 6 9 12 3
df2
# V1 V2 V3 V4
# 1 1 4 7 10
# 2 2 5 8 11
# 3 3 6 9 12
发布于 2014-02-05 19:16:18
正如您所提到的,结果确实略有不同,这意味着它们并不完全相等:
identical(data.frame(x),as.data.frame(x))
[1] FALSE
因此,您可能需要注意在使用哪一个时保持一致。
但也值得注意的是,as.data.frame
更快:
library(microbenchmark)
microbenchmark(data.frame(x),as.data.frame(x))
Unit: microseconds
expr min lq median uq max neval
data.frame(x) 71.446 73.616 74.80 78.9445 146.442 100
as.data.frame(x) 25.657 27.631 28.42 29.2100 93.155 100
y <- matrix(1:1e6,1000,1000)
microbenchmark(data.frame(y),as.data.frame(y))
Unit: milliseconds
expr min lq median uq max neval
data.frame(y) 17.23943 19.63163 23.60193 41.07898 130.66005 100
as.data.frame(y) 10.83469 12.56357 14.04929 34.68608 38.37435 100
https://stackoverflow.com/questions/21574250
复制相似问题