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.
df <- data.frame()
str(df)
'data.frame': 0 obs. of 0 variables
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With