初始化一个完整的空数据框(没有行,没有列)

时间:2016-06-07 01:11:47

标签: r dataframe

这是一个没有行而没有列的空数据框架

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

更智能的代码会产生虚假的列:

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

是否有非黑客替代方案?

创建这样的东西的原因是为了满足一个可以处理空数据帧而不是NULL的函数。

这与类似的问题不同,因为它没有列也没有行。

2 个答案:

答案 0 :(得分:7)

df <- data.frame()
str(df)
'data.frame':   0 obs. of  0 variables

答案 1 :(得分:2)

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