1

I would like to know what is the proper way to empty a data frame in R.

I need to keep colnames only.


Example:

id | fruit
---+------------
1  | strawberry
2  | blackberry
3  | apple
4  | peer

would, after the operation, be:

id | fruit
---+------------
txemsukr
  • 1,017
  • 1
  • 10
  • 32

2 Answers2

3

We can do

df <- df[FALSE, ]

#[1] id    fruit
#<0 rows> (or 0-length row.names)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
3
DF <- iris
str(DF[NULL,])
#'data.frame':  0 obs. of  5 variables:
#  $ Sepal.Length: num 
#$ Sepal.Width : num 
#$ Petal.Length: num 
#$ Petal.Width : num 
#$ Species     : Factor w/ 3 levels "setosa","versicolor",..: 
Roland
  • 127,288
  • 10
  • 191
  • 288