2016-06-07 27 views
3

这里是一个黑客建立无行空的数据帧,并没有列:初始化一个完整的空数据帧(没有行,没有列)

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的函数。

这不同于类似的问题,因为它是关于没有列以及没有行。

+1

但是,问题是有关指定列类型。 – nacnudus

+2

'structure(list(),class =“data.frame”)'将会成为你尝试添加一个类到列表的原始方法。 – thelatemail

+0

我不认为这是重复的 – thelatemail

回答

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

为什么我没有想到这一点? – nacnudus

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 
+0

性能真的是一个问题吗?唯一可能的缩放比例是重复。 –

+0

@JonathanCarroll你将如何缩放一个空的数据框? –

+0

@PierreLafortune这是我的观点。无论你采用哪种方式,这都不会是一个昂贵的过程。你可能会做很多次(在一些奇怪的情况下),但即使这样也不慢。 –