Create empty data frame with column names – R

It is easy to create a empty data frame, but some how tricky to create a empty data frame with columns defined. To create a simple empty data frame you do:

data_frame < - data.frame()

However no if you want to assign a value to a particular column in your data frame your first need to define column names. For that you can do:

data_frame < - data.frame(t(rep(NA,number_of_columns)))
//you can change number_of_columns according to your need

names(data_frame) <- c("column1","column2","column3","column4","column5","column6")
//Assign column names (i have assumed number_of_columns as 6)

data_frame <- data_frame[-1,]
//Remove all NAs

So now the data frame that you have is:

> data_frame
[1] column1 column2 column3 column4 column5 column6
<0 rows> (or 0-length row.names)
Tags: , , ,
Subscribe to Comments RSS Feed in this post

5 Responses

  1. This is great!. sometimes you need to create empty dataframes..

  2. That’s very useful. I’ve wanted to do this a lot, and this is the slickest way round the irritation.

  3. fine ! the simplest way to do this !

Leave a Reply

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

*
*