R 如何改进这个散列函数

R 如何改进这个散列函数,r,hash,R,Hash,是否有任何方法可以提高该散列的初始化速度? 目前在我的机器上大约需要20分钟 #prepare hash() hash <- list(); mappedV <- # matrix with more than 200,000 elements for( i in 1:nrow(mappedV) ) { hash[[paste(mappedV[i,], collapse = '.')]] <- 0; } #准备散列() hash通过预先分配所需长度的列表,而不是在每次迭

是否有任何方法可以提高该散列的初始化速度? 目前在我的机器上大约需要20分钟

#prepare hash()
hash <- list();

mappedV <- # matrix with more than 200,000 elements
for( i in 1:nrow(mappedV) ) {
  hash[[paste(mappedV[i,], collapse = '.')]] <- 0;
}
#准备散列()

hash通过预先分配所需长度的列表,而不是在每次迭代中增加列表,通常可以节省大量时间

瞧:

X <- vector(mode="list", 1e5)
Y <- list()

system.time(for(i in 1:1e5) X[[i]] <- 0)
#    user  system elapsed 
#     0.3     0.0     0.3 
system.time(for(i in 1:1e5) Y[[i]] <- 0)
#    user  system elapsed 
#   48.84    0.05   49.34 
identical(X,Y)
# [1] TRUE

X您还可以将
环境
作为哈希。。。让我们看看:

mappedV <- matrix(1:100000, ncol=5)
hash1 <- list()
hash2 <- new.env(hash=TRUE)

system.time(for(i in 1:nrow(mappedV)) hash1[[paste(mappedV[i,], collapse = '.')]] <- 0)
#   user  system elapsed 
# 19.263   1.321  21.634 

system.time(for(i in 1:nrow(mappedV)) hash2[[paste(mappedV[i,], collapse = '.')]] <- 0)
#   user  system elapsed 
#  0.426   0.002   0.430 

虽然速度不如使用环境快,但有一个简单的矢量化解决方案:

mappedV <- matrix(1:100000, ncol = 5)
hashes <- apply(mappedV, 1, paste, collapse = ".")

hash <- list()
hash[hashes] <- 0

mappedV我想你可以在这里使用环境查找或data.table,但我不清楚你想用它做什么。也许实际使用一个小样本数据集来处理这个问题,你的预期结果会得到更多的读者的响应。我用非常缓慢的方法来解决几年前的一些家庭作业。我们必须在一个非常大的矩阵中计算ceratain组合。上周我无意中发现了这一点,如果有更快的方法,我只是好奇。当然……是的,预分配是一种方法……但这里的OP看起来他试图分配列表的名称。。这里你的代码相当于
X[]哇,这太快了,现在不到一分钟。为什么要快得多?@Christian——因为每次添加新对象时,整个环境都不会被复制(而添加到列表时,整个环境都会被复制)。@Josh O'Brien——有什么网站效应需要我注意吗?@Christian:我用一个例子更新了我的答案,说明要注意wrt环境和不变性。希望对你们有帮助。谢谢大家。这是一个很好的答案。
mappedV <- matrix(1:100000, ncol = 5)
hashes <- apply(mappedV, 1, paste, collapse = ".")

hash <- list()
hash[hashes] <- 0
hash <- as.list(rep(0, length = length(hashes)))
names(hash) <- hashes