gpt4 book ai didi

performance - 将集合转换为 R 中的列索引的有效方法是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:38:11 26 4
gpt4 key购买 nike

概览

给一个大的(nrows > 5,000,000+)数据框,A,带有字符串行名和一个不相交集的列表(n = 20,000+),B,其中每个集合由 A 中的行名称组成,通过唯一值创建表示 B 中的集合的向量的最佳方法是什么?

插图

下面是一个说明这个问题的例子:

# Input
A <- data.frame(d = rep("A", 5e6), row.names = as.character(sample(1:5e6)))
B <- list(c("4655297", "3177816", "3328423"), c("2911946", "2829484"), ...) # Size 20,000+

期望的结果是:

# An index of NA represents that the row is not part of any set in B.
> A[,"index", drop = F]
d index
4655297 A 1
3328423 A 1
2911946 A 2
2829484 A 2
3871770 A NA
2702914 A NA
2581677 A NA
4106410 A NA
3755846 A NA
3177816 A 1

天真的尝试

类似这样的事情可以使用下面的方法来实现。

n <- 0
A$index <- NA
lapply(B, function(x){
n <<- n + 1
A[x, "index"] <<- n
})

问题

然而,由于多次索引 A 并且不是非常 R 风格或优雅,这非常慢(几个小时)。

如何快速高效地生成想要的结果?

最佳答案

这里有一个使用 base 的建议,与您当前的方法相比,它还算不错。

示例数据:

A <- data.frame(d   = rep("A", 5e6),
set = sample(c(NA, 1:20000), 5e6, replace = TRUE),
row.names = as.character(sample(1:5e6)))
B <- split(rownames(A), A$set)

基本方法:

system.time({
A$index <- NA
A[unlist(B), "index"] <- rep(seq_along(B), times = lapply(B, length))
})
# user system elapsed
# 15.30 0.19 15.50

检查:

identical(A$set, A$index)
# TRUE

为了更快,我想 data.table 会派上用场。

关于performance - 将集合转换为 R 中的列索引的有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13037560/

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