Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialise a complete empty data frame (no rows, no columns) [duplicate]

Tags:

dataframe

r

Here's a hack to create an empty data frame with no rows and no columns:

iris[FALSE, FALSE]
#> data frame with 0 columns and 0 rows

Smarter-looking code creates a spurious column:

x <- list(NULL)
class(x) <- c("data.frame")
attr(x, "row.names") <- integer(0)
str(x)
#> 'data.frame':    0 obs. of  1 variable:
#>  $ : NULL

Is there a non-hack alternative?

The reason to create such a thing is to satisfy a function that can handle empty data frames but not NULLs.

This is different from similar questions because it is about having no columns as well as no rows.

like image 343
nacnudus Avatar asked Jan 05 '23 22:01

nacnudus


2 Answers

df <- data.frame()
str(df)
'data.frame':   0 obs. of  0 variables
like image 53
Psidom Avatar answered Jan 10 '23 05:01

Psidom


empty.data.frame <- function() {
  structure(NULL,
            names = character(0),
            row.names = integer(0),
            class = "data.frame")
}
empty.data.frame()
#> data frame with 0 columns and 0 rows

# thelatemail's suggestion in a comment (fastest)
empty.data.frame2 <- function() {
  structure(NULL, class="data.frame")
}

library(microbenchmark)
microbenchmark(data.frame(), empty.data.frame(), empty.data.frame2())
#> Unit: microseconds
#>                 expr    min      lq     mean median     uq    max neval
#>         data.frame() 12.831 13.4485 15.18162 13.879 14.378 65.967   100
#>   empty.data.frame()  8.323  9.0515  9.76106  9.363  9.732 19.427   100
#>  empty.data.frame2()  5.884  6.9650  7.63442  7.240  7.540 17.746   100
like image 33
nacnudus Avatar answered Jan 10 '23 05:01

nacnudus