如何在R中初始化空数据帧(同时有很多列)
我找到了如何初始化3维或4维的空数据帧。就像如何在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) <-
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