R语言furrr包future_pmap维度错误问题求助
解决furrr::future_pmap报错"incorrect number of dimensions"的问题
问题重现
你的代码尝试用future_pmap并行运行函数,但触发维度错误:
library("furrr") library("parallel") testmatrix<-matrix(runif((20000*11),-1,21),nrow = 20000, ncol = 11) Testfunction<-function(ParVp,Ntrials){ for(simnum in 1:Ntrials){ Vp=ParVp[, 1:2] tp=ParVp[, 3:4] lg=ParVp[, 5:6] ld=ParVp[, 7:8] Tc=ParVp[, 9:10] rho=ParVp[, 11] print(head(Vp)) } } ncores<-detectCores()-2 plan(multisession, workers = ncores) Testoutput<- future_pmap(list(testmatrix,20),Testfunction) plan(sequential)
错误信息:
Error in (function (.l, .f, ..., .progress = FALSE) :
ℹ In index: 1.
Caused by error inParVp[, 1:2]:
! incorrect number of dimensions
错误原因
future_pmap的核心逻辑是按元素迭代传入的参数列表:
- 你传入的
list(testmatrix, 20)中,testmatrix作为矩阵会被拆解成单个数值元素(矩阵本质是带维度属性的向量)。 - 第一次迭代时,
ParVp拿到的是testmatrix[1]这个单个数值,而非完整矩阵。对单个数值执行矩阵索引操作ParVp[, 1:2],自然会触发维度错误。
你的需求是让函数运行20次,每次都传入完整的testmatrix,因此需要构造符合future_pmap要求的参数列表:每个参数对应的子元素数量必须等于你要运行的次数(20次)。
修正方案
方案1:运行函数20次(每次函数内部循环20次)
构造参数列表时,重复传入20次完整的testmatrix和20次20,确保每次迭代都能拿到完整矩阵:
library("furrr") library("parallel") testmatrix <- matrix(runif((20000*11), -1, 21), nrow = 20000, ncol = 11) Testfunction <- function(ParVp, Ntrials){ for(simnum in 1:Ntrials){ Vp <- ParVp[, 1:2] tp <- ParVp[, 3:4] lg <- ParVp[, 5:6] ld <- ParVp[, 7:8] Tc <- ParVp[, 9:10] rho <- ParVp[, 11] print(head(Vp)) } } ncores <- detectCores() - 2 plan(multisession, workers = ncores) # 生成20个完整矩阵和20个20的参数列表 Testoutput <- future_pmap(list(rep(list(testmatrix), 20), rep(20, 20)), Testfunction) plan(sequential)
方案2:并行执行20次模拟(替换函数内部的for循环)
如果你的目标是并行这20次模拟,而非在函数内部串行循环,可以重构函数为单次模拟逻辑,直接用future_pmap并行迭代:
library("furrr") library("parallel") testmatrix <- matrix(runif((20000*11), -1, 21), nrow = 20000, ncol = 11) # 单次模拟函数 SingleSim <- function(ParVp, simnum){ Vp <- ParVp[, 1:2] tp <- ParVp[, 3:4] lg <- ParVp[, 5:6] ld <- ParVp[, 7:8] Tc <- ParVp[, 9:10] rho <- ParVp[, 11] print(head(Vp)) # 可根据需求返回模拟结果,比如 return(list(Vp = Vp, sim_num = simnum)) } ncores <- detectCores() - 2 plan(multisession, workers = ncores) # 并行20次模拟,传入完整矩阵和模拟序号 Testoutput <- future_pmap(list(rep(list(testmatrix), 20), 1:20), SingleSim) plan(sequential)
内容的提问来源于stack exchange,提问作者OpenSauce
相关产品推荐
相关产品推荐

