R Quick Tips

How to create an empty data frame in R

empty data frame in R

Here is how to make an empty data frame in R only with column names. Choose between 4 different methods that you can use to achieve that, and decide which of those fits better for you.

Very helpful to make sure that combining data columns beginning always stays the same.

Create an empty data frame in R

Here is how to create an empty matrix in R that contains necessary rows and is used for the empty data frame. After that, the names of the columns are defined.

# create empty data frame
empty_df <- data.frame(matrix(ncol = 5, nrow = 0))
# define column names
names(empty_df) <- c("dt", "main", "description", "lat", "lon")

The next one is a conventional way to create an empty data frame with defined data types. Check them with function typeof.

empty_df <- data.frame(dt = double(),
                 main = character(),
                 description = character(),
                 lat = integer(),
                 lon = integer(),
                 stringsAsFactors = FALSE)

#[1] "double"

If you have an existing data frame, use that to create an empty one. Choose what you need and remove all data frame rows.

empty_df <-  iris[FALSE,]


#[1] Sepal.Length Sepal.Width  Petal.Length Petal.Width  Species     
#<0 rows> (or 0-length row.names)


A trick to create an empty data frame

There is the fourth option that is not so straightforward. I found that in this blog, and the idea is that the read.csv function inserts a string that contains necessary column names.
Normally that would be a CSV file, but technically contents of that are just separated values.

empty_df <-
    text = "dt, main, description, lat, lon",
    colClasses =  c("double", "character", "character", "integer", "integer")



An empty data frame is useful if you bind data frame rows together and ensure that the result contains everything necessary.
Here are examples of how to bind R data frame rows.

Here is another useful post to auto-detect column data types in the R data frame.

0 comments on “How to create an empty data frame in R

Leave a Reply

Your email address will not be published. Required fields are marked *