Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在R中初始化空数据帧(同时有很多列)_R_Dataframe - Fatal编程技术网

如何在R中初始化空数据帧(同时有很多列)

如何在R中初始化空数据帧(同时有很多列),r,dataframe,R,Dataframe,我找到了如何初始化3维或4维的空数据帧。就像 df <- data.frame(Date=as.Date(character()), File=character(), User=numeric(), stringsAsFactors=FALSE) df可能是这个- df <- data.frame(matrix(ncol = 10000, nrow = 0)) colnames(df) <-

我找到了如何初始化3维或4维的空数据帧。就像

df <- data.frame(Date=as.Date(character()),
             File=character(), 
             User=numeric(), 
             stringsAsFactors=FALSE)
df可能是这个-

df <- data.frame(matrix(ncol = 10000, nrow = 0))
colnames(df) <- paste0("hello", c(1:10000))

df我会使用
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"

是 啊这听起来不错。我想我需要的是一个矩阵,而不是一个数据框。如果你真的想把它强制成一行,你可以使用<代码> StIDENS 。@ WilmerEHenaoH,如果它解决了问题,请考虑接受答案。乔兰,好主意,更新了答案。相关:
df <- data.frame(matrix(ncol = 10000, nrow = 0))
colnames(df) <- paste0("hello", c(1:10000))
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"
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