Open In App

How to define dimensions of an empty DataFrame in R ?

Improve
Improve
Like Article
Like
Save
Share
Report

An empty data frame in R Programming Language corresponds to the tabular structure where the axes are of length 0, i.e. it does not contain any data items. It is basically a tabular structure organized into rows and columns consisting of all empty data vectors. A data frame can be empty in the following cases : 

  • A data frame with empty vectors.
  • Creating a data frame of NULL entries.

Method 1: Defining the dataframe with empty vectors. 

An empty data frame can be created by using only 0-length variables for column names. The data types can also be declared for these columns to specify the type of data if we wish to. In this case, the dimensions of the data frame are 0 x number of columns, but the data frame is considered empty, since it doesn’t contain any entries. 

Syntax:

data.frame(column1 = data_type(col1),…)

Example

R




# declaring a data frame with 2 columns and
# declaring data type of both the columns 
data_frame <- data.frame(col1 = character(0), col2 = numeric(0))
  
# printing data frame
print ("Data Frame : ")
print (data_frame)


Output

[1] “Data Frame : “

[1] col1 col2

<0 rows> (or 0-length row.names)

In case, a single type of data type is to be assigned to all the columns of the data frame, the data type can be declared after all the columns are initialized with NA values. 

Example

R




# declaring an empty data frame
data_frame1 <- data.frame(col1=NA, col2=NA, col3=NA, col4=NA)
[numeric(0), ]
  
# printing data frame
print ("Data Frame :")
print (data_frame1)


Output

[1] “Data Frame : “

[1] col1 col2 col3 col4

<0 rows> (or 0-length row.names)

Method 2 : Matrix with NULL as values

This is just another way of interpreting empty dataframe. Here, the values it stores will be NULL, but the dimension will be like a regular dataframe with values. A matrix with the required dimensions can be created. It is filled with NA or missing values. Since, the matrices and data frames are interconvertible into each other, it can then be converted to data frame. The dimensions of the data frame are equivalent to the length of the axes declared for matrix. A matrix can be declared using matrix() function in R. 

Example:

R




# declaring a data frame with 2 columns
# and declaring data type of both the 
# columns 
mat <- matrix(NA, nrow = 5, ncol = 2)
  
# converting matrix to data frame
data_frame <- data.frame(mat)
  
# printing data frame
print ("Data Frame : ")
print (data_frame)
  
# printing dimensions
dim(data_frame)


Output

[1] “Data Frame : “

 X1 X2

1 NA NA

2 NA NA

3 NA NA

4 NA NA

5 NA NA

[1] 5 2



Last Updated : 21 Apr, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads