Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dataframe

r

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 
like image 423
Ophelie Avatar asked Feb 05 '14 10:02

Ophelie


People also ask

What is difference between Dataframe and as data frame?

frame() can be used to build a data frame while as. data. frame() can only be used to coerce other object to a data frame.

What does as data frame do in R?

as. data. frame() function in R Programming Language is used to convert an object to data frame. These objects can be Vectors, Lists, Matrices, and Factors.

How do I convert a Dataframe to a data table in R?

Method 1 : Using setDT() method The setDT() method can be used to coerce the dataframe or the lists into data. table, where the conversion is made to the original dataframe. The modification is made by reference to the original data structure.

Which function coerces an existing object to a data frame if possible?

as_tibble() turns an existing object, such as a data frame or matrix, into a so-called tibble, a data frame with class tbl_df .


1 Answers

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 
like image 81
Brandon Bertelsen Avatar answered Sep 28 '22 04:09

Brandon Bertelsen