与在矩阵和 data.frame/data.table 中一样(尽管与矩阵不同),数据是按列存储的,您可以先转置它:
as.vector(t(example))
# [1] "A" "B" "B" "C" "C" "B" "A" "C" "A" "B" "B" "C" "C" "C"
基准测试包括 @Sotos、@Frank 和 @Wen 使用虚拟数据集提供的选项:
example <- as.data.table(matrix(sample(LETTERS, 10^7, replace = T), ncol = 1000))
dim(example)
#[1] 10000 1000
library(microbenchmark)
psidom <- function() as.vector(t(example))
sotos <- function() c(t(example))
frank <- function() unlist(transpose(example), use.names = FALSE)
wen <- function() unname(unlist(data.frame(t(example))))
# data.table 1.10.4
microbenchmark(psidom(), sotos(), frank(), wen(), times = 10)
#Unit: milliseconds
# expr min lq mean median uq max neval
# psidom() 163.5993 178.9236 393.4838 198.6753 632.1086 1352.012 10
# sotos() 186.8764 188.3734 467.2117 343.1514 618.3121 1221.721 10
# frank() 3065.0988 3493.3691 5315.4451 4649.4643 5742.2399 9560.642 10
# wen() 7316.6743 8497.1409 9200.4397 9038.2834 9631.5313 11931.075 10
data.table dev 版本 1.10.5 中的另一个测试:
# data.table 1.10.5
psidom <- function() as.vector(t(example))
sotos <- function() c(t(example))
frank <- function() unlist(transpose(example), use.names = FALSE)
fast <- function() `attributes<-`(t(example), NULL)
microbenchmark(psidom(), sotos(), frank(), fast(), times = 10)
#Unit: milliseconds
# expr min lq mean median uq max neval
# psidom() 228.1248 246.4666 271.6772 256.9131 287.5072 354.2053 10
# sotos() 254.3512 280.2504 315.3487 322.5726 344.7125 390.3482 10
# frank() 290.5476 310.7076 374.6267 349.8021 431.8451 491.9301 10
# fast() 159.6006 167.6316 209.8363 196.8821 272.4758 281.3146 10