Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...