[問題] foreach 與 Parallel 回傳多個matrix?

看板R_Language作者 (5566520)時間8年前 (2017/03/08 23:19), 編輯推噓1(102)
留言3則, 1人參與, 最新討論串1/3 (看更多)
文章分類提示: - 問題: 當你想要問問題時,請使用這個類別。 [問題類型]: 程式諮詢(我想用R 做某件事情,但是我不知道要怎麼用R 寫出來) [軟體熟悉度]: 新手(沒寫過程式,R 是我的第一次) [問題敘述]: 原本程式會有兩個global變數,去承接for loop內的數值,但由於效能的關係 目前想把for loop改為 Parallel的方式,但僅查詢到回傳一個的方式, 是有解法可以處理這種狀況呢? 原始情境: df <- NULL df1 <- NULL for(i in 1:10000){ # 經運算後得到temp與temp1 temp <- c(1,2,3,4) temp1 <- c(1,2,3,4) df <- rbind(df,temp) df1 <- rbind(df1, temp1) } [程式範例]: library(foreach) library(doParallel) #setup parallel backend to use many processors cores=detectCores() cl <- makeCluster(cores[1]-1) #not to overload your computer registerDoParallel(cl) finalMatrix <- foreach(i=1:150000, .combine=cbind) %dopar% { tempMatrix = functionThatDoesSomething() #calling a function #do other things if you want tempMatrix #Equivalent to finalMatrix = cbind(finalMatrix, tempMatrix) } #stop cluster stopCluster(cl) Ref: http://tinyurl.com/hdmlpsh [環境敘述]: Win7 64bit, R 3.3.1 [關鍵字]: Parallel -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.195.56.139 ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1488986361.A.F22.html

03/09 12:31, , 1F
dtcomb <- function(...) {rblindlist(list(...))}
03/09 12:31, 1F

03/09 12:33, , 2F
out <- foreach(..,.combine="dtcomb",..) %dopar% {..
03/09 12:33, 2F

03/09 12:34, , 3F
... return(your_temp_dataframe)})
03/09 12:34, 3F
文章代碼(AID): #1Om23vyY (R_Language)
文章代碼(AID): #1Om23vyY (R_Language)