我想用 foreach 回圈替換 for 回圈,但我得到一個錯誤“unexpected token in”。下面你可以看到我的代碼。只是提到所有的 f 都是檔案名。你有什么主意嗎?
for (f in file) {
print(f)
analyze(f)
tmp <- res4
y <- rbind(y, tmp)
}
uj5u.com熱心網友回復:
這是一個使用順序運算子的簡單foreach回圈%do%。
請注意,vector 的前 2 個值file是 的輸出print。
library(foreach)
file <- c("/data/an_01h.dat", "/data/an_01h.dat")
foreach (f=file) %do% {
print(f)
}
#> [1] "/data/an_01h.dat"
#> [1] "/data/an_01h.dat"
#> [[1]]
#> [1] "/data/an_01h.dat"
#>
#> [[2]]
#> [1] "/data/an_01h.dat"
由reprex 包于 2022-04-21 創建(v2.0.1)
和一個并行回圈。該%dopar%運算子是一個可并行化的運算子。這次print不顯示其輸出,請參閱this SO question on this。
library(foreach)
library(doParallel)
#> Loading required package: iterators
#> Loading required package: parallel
file <- c("/data/an_01h.dat", "/data/an_01h.dat")
ncores <- detectCores() - 1L
registerDoParallel(ncores) # use multicore, set to the number of our cores
foreach (f=file) %dopar% {
print(f)
}
#> [[1]]
#> [1] "/data/an_01h.dat"
#>
#> [[2]]
#> [1] "/data/an_01h.dat"
由reprex 包于 2022-04-21 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/462010.html
上一篇:如何按條件將代碼應用于資料幀?
