57

Is there a quick way to initialize an empty data frame? If you know what the dimensions will be? For example:

Suppose I would like a blank data frame that has 100 rows and 10:

x <- data.frame(1:100,2,3,4,5,6,7,8,9,10) 
dim(x) ## that's right

But suppose I want something like 300 columns? How do I quickly initialize columns in a data.frame?

x <- data.frame(1:100,2,3,4,5 ....) ## *cries*
Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
Brandon Bertelsen
  • 43,807
  • 34
  • 160
  • 255

2 Answers2

77
> df <- data.frame(matrix(ncol = 300, nrow = 100))
> dim(df)
[1] 100 300
Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
36

I always just convert a matrix:

x <- as.data.frame(matrix(nrow = 100, ncol = 10))
Matt Parker
  • 26,709
  • 7
  • 54
  • 72
  • Thanks Matt! Looks like Gavin beat you to the type :P – Brandon Bertelsen Feb 01 '11 at 23:13
  • 1
    @Brandon actually @Matt beat me to it. I blame adding the `dim(df)` output for that ;-) – Gavin Simpson Feb 01 '11 at 23:16
  • 1
    Hmm, you proved the dimensions and actually used the number of columns specified in the question; what counts more toward bestfulness? It's probably unwise to contribute toward my ability to edit other people's posts, anyway... – Matt Parker Feb 01 '11 at 23:21