Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

r - Difference between as.data.frame(x) and data.frame(x)

What is the difference between as.data.frame(x) and data.frame(x)

In this following example, the result is the same at the exception of the columns names.

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
question from:https://stackoverflow.com/questions/21574250/difference-between-as-data-framex-and-data-framex

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As mentioned by Jaap, data.frame() calls as.data.frame() but there's a reason for it:

as.data.frame() is a method to coerce other objects to class data.frame. If you're writing your own package, you would store your method to convert an object of your_class under as.data.frame.your_class(). Here are just a few examples.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...