gpt4 book ai didi

R从List列表中提取元素的快速方法

转载 作者:行者123 更新时间:2023-12-01 23:13:13 25 4
gpt4 key购买 nike

大家好,我正在处理包含列表的大型列表。每个子列表都包含 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

但我的列表包含数千个元素,并且我多次执行此操作。那么,有没有更快的方法来做上面的操作呢?

最好的问候,

马里奥

最佳答案

如果您多次这样做,那么最好将您的列表转换为更简单的结构,例如 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

或者,如果你想保留基础 R,你可以使用 rbind

res = do.call(rbind.data.frame, l)$C # or [[3]]

这会让事情变得更容易吗?

更新

以下是一些基准,展示了该问题的不同解决方案:

准备工作:

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))

基准测试:

# 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
)

结果:

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

(1) 一般来说,最好首先使用类似于 data.frame 或 data.table 的表结构 - 从这些结构中选择列花费最少的时间。

(2) 如果无法做到这一点,最好先将列表转换为 data.frame 或 data.table,而不是在一次操作中提取值。

(3) 有趣的是,将 sapply 或 lapply 与基本 R(优化)[[-函数一起使用会导致处理时间仅比使用 rbind 和提取值作为列的两倍差。

关于R从List列表中提取元素的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27191657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com