Ama*_*mar 0 parallel-processing r
我试图使用foreach和将以下代码转换为并行%dopar%.
library(doSNOW)
library(foreach)
cl<- makeCluster(4, type = "SOCK")
registerDoSNOW(cl)
min_subid <- c()
max_subid <- c()
p_typ <- c()
p_nm <- c()
st_tm<-c()
end_tm <- c()
supp <- c()
chart_type <- c()
foreach(j =1:noOfPhases) %dopar%
{
start_time <-phases[j, colnames(phases)=="StartTime"]
end_time <-phases[j, colnames(phases)=="StopTime"]
phase_type <-phases[j, colnames(phases)=="Phase_Type_Id"]
phase_name <-phases[j, colnames(phases)=="Phase_Name"]
suppress <-phases[j, colnames(phases)=="Suppression_Time"]
chart_typ <-phases[j, colnames(phases)=="chartType"]
conft<-(masterData$Time.Subgroup>=start_time & masterData$Time.Subgroup<=end_time)
masterData[which(conft), colnames(masterData)=="Phase_Type"]<-phase_type
masterData[which(conft), colnames(masterData)=="Phase_Name"]<-phase_name
min_subid <- rbind(min_subid, min(which(conft)))
max_subid <- rbind(max_subid, max(which(conft)))
p_typ <- rbind( p_typ, masterData$Phase_Type[min(which(conft))])
p_nm <- rbind( p_nm, masterData$Phase_Name[min(which(conft))])
st_tm <- rbind( st_tm, as.character(start_time))
end_tm <- rbind( end_tm, as.character(end_time))
supp <- rbind(supp,as.character(suppress))
chart_type <- rbind(chart_type,as.character(chart_typ))
phase_info <- data.frame(Subgrp_No_Start=min_subid, Subgrp_No_End=max_subid, Phase_Type=p_typ,
Phase_Name=p_nm, Start_Time=st_tm, Stop_Time=end_tm,
Suppression_Time=supp,ChartType=chart_type)
}
phase_output<-merge(phase_info, phases, by.x=c("Start_Time",
"Stop_Time","ChartType"), by.y=c("StartTime", "StopTime","chartType"))
Run Code Online (Sandbox Code Playgroud)
%do%包含而不是上面的代码执行成功%dopar%.任何人都可以帮助我理解为什么我运行parallel(%dopar%)并在顺序(%do%)上成功运行时出现以下错误
Error in merge(phase_info, phases, by.x = c("Start_Time", "Stop_Time", :
object 'phase_info' not found
Run Code Online (Sandbox Code Playgroud)
解决方案非常简单,但我首先解释了执行代码来解释错误时发生的情况.
foreach块中发生的phase_info是为每个值创建一个数据帧()j,它们在列表中一起返回.但是,由于您的分配phase_info <- data.frame(...)位于foreach而不是外部,因此列表不会存储在任何位置并被丢弃.混淆的原因是,在使用时,%do%您在主节点上按顺序创建所有数据帧%dopar%,并且在工作节点上并行创建帧时.以下merge命令导致错误如果使用在主节点上执行%dopar%,因为phase_info在其工作区,不存在.另请注意,在使用%do%上述内容时,每次迭代都会foreach覆盖先前迭代的结果(即只获得最后一次迭代的结果).
这个小改动修复了它:
phase_info <- foreach(...) %dopar% {
...
data.frame(Subgrp_No_Start=min_subid, Subgrp_No_End=max_subid, Phase_Type=p_typ,
Phase_Name=p_nm, Start_Time=st_tm, Stop_Time=end_tm,
Suppression_Time=supp,ChartType=chart_type)
# No need to give it a name as it will be returned and the name forgotten
}
phase_output <- merge(phase_info, ...)
Run Code Online (Sandbox Code Playgroud)
如上所述,phase_info现在将是一个列表,其中每个元素都是数据框.我现在只是猜测,但你可能想要执行mergeelementwise,就像这样:
phase_output <- lapply(phase_info, merge, phases, by.x=c("Start_Time",
"Stop_Time","ChartType"), by.y=c("StartTime", "StopTime","chartType"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
736 次 |
| 最近记录: |