# Create Empty Data Frame in R

Sheeraz Gul May 13, 2022

The empty data frame means a tabular structure where the length of axes is 0. There are two methods of creating empty data frames.

This tutorial demonstrates how to create an empty data frame in R.

## Create a Matrix and Convert It to Data Frame in R

The matrix and data frame can easily be converted to each other. To create an empty data frame, we create an empty matrix with length 0 for both columns and rows and convert it to a data frame.

Let’s try an example.

``````# create a matrix
demo_matrix = matrix(ncol = 0, nrow = 0)

# convert the matrix to data frame
delftstack=data.frame(demo_matrix)
# Print data frame
print(delftstack)

# dimensions of the data frame
print("The Dimensions of the data frame")
dim(delftstack)
``````

The code above creates an empty matrix, converts it to a data frame, and finally shows its dimensions. See output:

``````data frame with 0 columns and 0 rows

 "The Dimensions of the data frame"
 0 0
``````

We can also create an empty data frame without specifying the column names because we can pass empty vectors as arguments.

``````# declare empty data frame with 4 columns and null entries
delftstack = data.frame(matrix( vector(), 0, 4, dimnames=list(c(), c("C1","C2","C3","C4"))),
stringsAsFactors=F)

# print the data frame
print ("The Empty dataframe is")
print (delftstack)
``````

This code will create an empty data frame with four empty columns. See output:

`````` "The Empty dataframe is"
 C1 C2 C3 C4
<0 rows> (or 0-length row.names)
``````

## Initialize Empty Vectors to Create Empty Data Frame in R

This method defines a data frame as a set of empty vectors with a class type. We must specify `stringsAsFactors=False` so that any character vectors can be treated as strings.

See example:

``````#data frame with 5 empty vectors
delftstack <- data.frame(Doubles=double(),
Integers=integer(),
Factors=factor(),
Logicals=logical(),
Characters=character(),
stringsAsFactors=FALSE)

#the data frame structure
str(delftstack)
``````

The code above creates an empty data frame with five empty vectors and then shows the structure of the data frame. See output:

``````'data.frame':	0 obs. of  5 variables:
\$ Doubles   : num
\$ Integers  : int
\$ Factors   : Factor w/ 0 levels:
\$ Logicals  : logi
\$ Characters: chr
``````
Author: Sheeraz Gul

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.