2014-04-29 37 views
1

有人能解釋我在這裏發生了什麼?
我有我需要匹配一個表列出的清單,我使用lapplyfmatch(包fastmatch http://cran.r-project.org/web/packages/fastmatch/index.html)爲(我認爲使用由哈希表的匹配與匹配,與匹配相反)。
但是,如果必須在函數中評估表值(至少這是我所懷疑的),那麼這很慢,但我不完全確定。
我發現了一種解決方法,可以將計算速度從5.5秒提高到0.01秒,但希望獲得更優雅的解決方案。
這裏是一個重複的例子:
奇怪的b​​ahaviour與lapply,懶惰的評價?

set.seed(10) 

matchFeatures <- replicate(n = 1000, paste0("a", sample(x = 1:10000, size = sample(x = 1:10, size = 1)))) 
matchTable <- 1:10000 

system.time(m1 <- lapply(matchFeatures, function(features) fmatch(features, paste0("a", 1:10000)))) 
system.time(m2 <- lapply(matchFeatures, function(features) force(fmatch(features, paste0("a", 1:10000))))) 
system.time({tempTable <- paste0("a", 1:10000); m3 <- lapply(matchFeatures, function(features) fmatch(features, tempTable))}) 
identical(m1, m3) 

感謝賈斯汀,只是跟進,我一直在尋找這樣的事情:

system.time(m4 <- lapply(matchFeatures, fmatch, table = paste0("a", 1:10000))) 

回答

2

在前兩個功能,你正在運行paste命令每次迭代一次(即10000次)。第三,它只發生一次。如果您使用matchTable <- paste('a', 1:10000)並將matchTable傳遞到所有三個版本,則會像預期的那樣獲得顯着的加速。

matchFeatures <- replicate(n = 1000, 
          paste0("a", 
          sample(x = 1:10000, 
            size = sample(x = 1:10, size = 1)))) 
matchTable <- paste('a', 1:10000) 

system.time(m1 <- lapply(matchFeatures, 
         function(features) fmatch(features, matchTable))) 
system.time(m2 <- lapply(matchFeatures, 
         function(features) force(fmatch(features, matchTable)))) 
system.time(m3 <- lapply(matchFeatures, 
         function(features) fmatch(features, matchTable))) 
identical(m1, m3) 
+0

有道理,謝謝 – arunasm