2016-06-07 68 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這是我的觀點。無論你採用哪種方式,這都不會是一個昂貴的過程。你可能會做很多次(在一些奇怪的情況下),但即使這樣也不慢。 –