我会做到这一点使用setDF
(或setDT
,如果你喜欢data.table
作为输出)和setnames
:
library(data.table)
DF <- setnames(setDF(lapply(integer(1e4), function(...) character(0L))),
paste0("hello", 1:1e4))
head(names(DF))
# [1] "hello1" "hello2" "hello3" "hello4" "hello5" "hello6"
两个步骤(setnames
和setDF
)比base
同行更有效率,因为无份制成。
的基准:
library(microbenchmark)
microbenchmark(times = 1000,
base = {df <- data.frame(matrix(ncol = 10000, nrow = 0))
colnames(df) <- paste0("hello", c(1:10000))},
DT = setnames(setDF(lapply(integer(1e4),
function(...) character(0L))),
paste0("hello", 1:1e4)))
# Unit: milliseconds
# expr min lq mean median uq max neval cld
# base 26.77218 30.94223 37.30173 36.76721 37.80338 102.2379 1000 b
# DT 16.68004 23.18865 30.60573 29.18421 36.03590 178.1045 1000 a
相关:[*创建一个空data.frame *](http://stackoverflow.com/questions/10689055/create-an-empty-data-frame) – Jaap