Skip to content
Related Articles

Related Articles

Difference Between as.data.frame() and data.frame() in R

View Discussion
Improve Article
Save Article
  • Last Updated : 02 Aug, 2022
View Discussion
Improve Article
Save Article

R Programming Language contains a large number of data structures, data frames being very crucial in it. It is used to organize the data in a well-arranged tabular manner. Data frames can both be created from scratch as well as other data objects can be converted to data frames easily using large inbuilt R methods. 

as.data.frame()

The as.data.frame() method in R is used to check if a particular R object is a data frame or not.  If not, it is used to convert the R objects into the data frame object. The objects taken as arguments may be vectors, lists or matrices. It is an in-built method in R. The as.data.frame method has the following syntax : 

Syntax: as.data.frame(obj)

Arguments : 

obj – Vectors, lists or matrices which can be converted to the data frame objects. 

The following code snippet illustrates the conversion of a list object to a data frame. 

R




#creating vectors
vec_a <- c(0,1,2)
vec_b <- letters[1:3]
vec_c <- TRUE
  
#creating a list of vectors
lst <- list( vec_a , vec_b, vec_c)
print("List Vector")
print(lst)
  
#convert to data frame
df <- as.data.frame(lst)
print("Data Frame")
print(df)

Output

[1] "List Vector" 
[[1]] 
[1] 0 1 2  
[[2]] 
[1] "a" "b" "c"  
[[3]] 
[1] TRUE  
[1] "Data Frame" 
c.0..1..2. c..a....b....c.. TRUE. 
1          0                a  TRUE 
2          1                b  TRUE 
3          2                c  TRUE

data.frame()

The data.frame method in R is used to create a data frame object into the R working space. It is an in-built method in R Programming Language. 

R




#creating the data frame by defining the x and y coordinates respectively
x_pos <- 1:10
#defining the y axis 
y_pos = 5:14
#creating the data frame
data_frame = data.frame(x_pos, y_pos )
print("Data Frame")
print(data_frame)

Output

[1] "Data Frame"
   x_pos y_pos
1      1     5
2      2     6
3      3     7
4      4     8
5      5     9
6      6    10
7      7    11
8      8    12
9      9    13
10    10    14

Difference Between as.data.frame() and data.frame() in R

data.frameas.data.frame
Used to create objectUsed to coerce object
SlowerargumentsTime complexity is less, which implies it is faster
All variables of the data frame have to be specified as argument of the methodR objects are supplied as input arguments to the method

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!