14

Here is how I can do that:

df <- data.frame(a=1:200)
df$a <- NULL
df

Result:

data frame with 0 columns and 200 rows

Can the same be achieved with only one command?

Jaap
  • 81,064
  • 34
  • 182
  • 193
January
  • 16,320
  • 6
  • 52
  • 74
  • 4
    I guess the first question that comes to mind is _"Why?"_. Spidey-sense says you're going to use a `for` loop to try to fill this and there is probably a better way if you post what you're trying to achieve. – hrbrmstr Jul 29 '15 at 13:41
  • Also check [here](http://stackoverflow.com/questions/9917545/r-define-dimensions-of-empty-data-frame) and [here](http://stackoverflow.com/questions/10689055/create-an-empty-data-frame) – akrun Jul 29 '15 at 13:45
  • 1
    @hrbrmstr, Nah, that was just curiosity. I know what you are thinking, and yes, I do combine lapply with Reduce for the same effect. – January Jul 29 '15 at 13:54

3 Answers3

34

This can work (if the call to 2 functions is not considered 2 commands):

data.frame(matrix(, nrow=200, ncol=0))
#data frame with 0 columns and 200 rows

Edit: Another option is data.frame()[1:200, ]:

data.frame()[1:200, ]
# data frame with 0 columns and 200 rows
Cath
  • 23,906
  • 5
  • 52
  • 86
  • R says "missing agument" in `matrix` – Sashko Lykhenko Sep 20 '17 at 22:37
  • 1
    @SashkoLykhenko which version of `R` ? (it works as expected with R 3.3.0) – Cath Sep 21 '17 at 06:54
  • 3
    data.frame(matrix(nrow=200, ncol=0)) this works as well – Dimitrios Zacharatos Dec 14 '18 at 16:46
  • @Cath data.frame()[1:10, ] creates an empty data frame but while using a loop to fill values in this, we get weird row names. df = data.frame()[1:10, ] for (i in 1:10){ x = i+2 y = i+20 df$x = x df$y = y } df – Dr Nisha Arora May 30 '21 at 04:08
  • 1
    @DrNishaArora when creating the empty data.frame, `row.names` are set to `NA` followed by indices to avoid duplicated row.names. (This said, I doubt your loop will give you the output you're looking for) – Cath May 31 '21 at 06:32
  • @Cath Yup, so either we reset rownames later or we start with a non-empty data frame (with one row) & delete the first row later. Thanks – Dr Nisha Arora May 31 '21 at 12:28
  • @DrNishaArora note that if you already know what you want to put in the data.frame, there is no need to create an empty one – Cath May 31 '21 at 12:35
13

What about this?

data.frame(row.names = 1:200)
Paul
  • 383
  • 4
  • 14
4

This is what I discovered via dput:

structure(
   list(), 
   .Names = character(0), 
   row.names = c(NA, -200L), 
   class = "data.frame"
 )
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
wush978
  • 3,114
  • 2
  • 19
  • 23