146

Possible Duplicate:
Create an Empty Data.Frame

I need to create an empty data frame in R with specified column names. Any simplest way ?

0

2 Answers 2

176

Just create a data.frame with 0 length variables

eg

nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)

## 'data.frame':    0 obs. of  3 variables:
##  $ x: num 
##  $ y: int 
##  $ z: Factor w/ 0 levels: 

or to create a data.frame with 5 columns named a,b,c,d,e

nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))
Sign up to request clarification or add additional context in comments.

2 Comments

why does z convert to Factor?
@pssguy because of the default behaviour of data.frame, and specifically the default value for the argument stringsAsFactors = T.
16

Perhaps:

> data.frame(aname=NA, bname=NA)[numeric(0), ]
[1] aname bname
<0 rows> (or 0-length row.names)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.