我正在用 R 撰寫蒙特卡羅模擬,我需要執行 100,000 次。我遇到了一些效率問題。我遇到的一個關鍵效率問題是我在較大的 Monte Carlo for 回圈內有一個 for 回圈。如果可能的話,我想嘗試洗掉這個回圈,但目前我很困惑。
我有一個資料框,其中包含一個值以及一個開始和結束,它們是最終矩陣的索引。
這是一個示例代碼片段:
a <- data.frame( value = c( 3, 10, 5, 8),
start = c(2, 3, 4, 5),
end = c( 9, 10, 9, 8 ))
b <- matrix( 0, nrow = nrow(a), ncol = 10)
# this is the for loop that I would like to remove
for ( i in 1:nrow(a) ) {
b[ i, a$start[i]:a$end[i] ]<- a$value[i]
}
感覺好像我應該能夠將問題重新構建為某種型別的連接,但我一直無法取得進展。任何幫助表示贊賞。
uj5u.com熱心網友回復:
矢量帶rep.int,sequence以及矩陣索引:
len <- a$end - a$start 1
b[matrix(c(rep.int(1:nrow(a), len), sequence(len, a$start)), ncol = 2)] <- rep.int(a$value, len)
在更大的資料集上,矢量化版本的速度提高了 13 倍以上:
a <- data.frame(value = sample(10, 1e5, replace = TRUE),
start = sample(5, 1e5, replace = TRUE),
end = sample(6:10, 1e5, replace = TRUE))
b <- matrix(0, nrow = nrow(a), ncol = 10)
vecfill <- function(a, b) {
len <- a$end - a$start 1
b[matrix(c(rep.int(1:nrow(a), len), sequence(len, a$start)), ncol = 2)] <- rep.int(a$value, len)
return(b)
}
iterfill <- function(a, b) {
for ( i in 1:nrow(a) ) {
b[ i, a$start[i]:a$end[i] ]<- a$value[i]
}
return(b)
}
microbenchmark::microbenchmark(vecfill(a, b), iterfill(a, b), times = 100)
#> Unit: milliseconds
#> expr min lq mean median uq max neval
#> vecfill(a, b) 19.5291 19.99705 24.72165 21.01205 24.0373 75.8988 100
#> iterfill(a, b) 292.6082 310.52755 330.09472 319.50020 331.3736 560.9486 100
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/362029.html
上一篇:顯示當前活動的圓點滑動滑塊
