大家好,我正在处理大型列表,其中包含列表.每个子列表包含n个元素.我总是希望获得第三名,例如
l = list()
l[[1]] = list(A=runif(1), B=runif(1), C=runif(1))
l[[2]] = list(A=runif(1), B=runif(1), C=runif(1))
l[[3]] = list(A=runif(1), B=runif(1), C=runif(1))
res = sapply(l, function(x) x$C)
res = sapply(l, function(x) x[[3]]) #alternative
Run Code Online (Sandbox Code Playgroud)
但我的列表包含数千个元素,我正在执行此操作很多次.那么,上面的操作有更快的方法吗?
Beste问候,
马里奥
如果你多次这样做,那么将列表转换为更简单的结构会更好data.table.
library(data.table)
DT=rbindlist(l);
res = DT$C
# or if you prefer the 3rd element, not necessarily called 'C' then:
res = DT[[3]] # or DT[,C] which might be faster. Please check @richard-scriven comment
Run Code Online (Sandbox Code Playgroud)
或者,如果你想保留基础R你可以使用 rbind
res = do.call(rbind.data.frame, l)$C # or [[3]]
Run Code Online (Sandbox Code Playgroud)
这会让事情变得更容易吗?
UPDATE
以下是一些基准测试,显示了该问题的不同解决方案:
准备工作:
library(data.table)
library(microbenchmark)
# creating a list and filling it with items
nbr = 1e5;
l = vector("list",nbr)
for (i in 1:nbr) {
l[[i]] = list(A=runif(1), B=runif(1), C=runif(1))
}
# creating data.frame and data.table versions
DT <- rbindlist(l)
DF <- data.frame(rbindlist(l))
Run Code Online (Sandbox Code Playgroud)
基准测试:
# doing the benchmarking
op <-
microbenchmark(
LAPPLY.1 = lapply(l, function(x) x$C),
LAPPLY.2 = lapply(l, `[`, "C"),
LAPPLY.3 = lapply(l, `[[`, "C"),
SAPPLY.1 = sapply(l, function(x) x$C),
SAPPLY.2 = sapply(l, function(x) x[[3]]),
SAPPLY.3 = sapply(l, `[[`, 3),
DT.1 = rbindlist(l)$C,
DT.2 = DT$C,
DF.2 = DF$C,
times = 100
)
Run Code Online (Sandbox Code Playgroud)
结果:
op
## Unit: microseconds
## expr min lq mean median uq max neval
## LAPPLY.1 124088 142390 161672 154415 163240 396761 100
## LAPPLY.2 111397 134745 156012 150062 165229 364539 100
## LAPPLY.3 66965 71608 82975 77329 84949 323041 100
## SAPPLY.1 133220 149093 166653 159222 172495 311857 100
## SAPPLY.2 105917 119533 137990 133364 139216 346759 100
## SAPPLY.3 70391 74726 81910 80520 85792 110062 100
## DT.1 46895 48943 49113 49178 49391 51377 100
## DT.2 8 18 37 47 49 58 100
## DF.2 7 13 33 40 42 82 100
Run Code Online (Sandbox Code Playgroud)
(1)一般来说,最好首先使用像data.frame或data.table这样的结构表 - 从那些成本中选择列的时间最少.
(2)如果不可能,最好先将列表转换为data.frame或data.table,然后在一次操作中提取值.
(3)有趣的是,使用基础R(优化)[[函数的蓝宝石或lapply 导致处理时间仅是使用rbind的两倍,而不是将值提取为列.