【问题标题】:How to use R str_detect on multiple cores如何在多核上使用 R str_detect
【发布时间】:2016-01-11 00:18:31
【问题描述】:

我正在尝试使用 foreach 在 R 中运行一个循环,以便在多个核心上进行字符串检测,但我发现它只在一个核心上运行,我无法让它在多个核心上运行。

    library("parallel")
library("foreach")
library("doParallel")

#How to detect how many cores are on the server
detectCores()

cl <- makeCluster(3)
registerDoParallel(cl)

x<-c("Hello My Name is", "Happy Birthday", "Hi How are you today? My Name is walley", "Nice to meet you", "Best friends")
y<-c("Hello", "Birthday", "Hi", "Nice", "Best friends")

foreach(i = 1:length(y)) %dopar%{

print(i)
if (sum(str_detect(x,paste("\\b",as.character(y),"\\b", sep=""))) > 0){

    str_replace(x[i], as.character(y[which(str_detect(x[i],paste("\\b",as.character(y),"\\b", sep="")) == TRUE)]), "")
    }
}

write.csv(mycatalog, "Matching.csv")
getDoParWorkers()

stopCluster(cl)

【问题讨论】:

  • 这是不可重现的。请将您的示例归结为一个小的、可重现的示例。
  • 好的,这是新修改的更简单的代码。我创建了两个向量 x 和 y,我的想法是匹配 y 的每个元素,如果它在 x 中遇到并替换这个元素。
  • 函数str_detectstr_replace从何而来?
  • 来自 R 库(stringr) 库(Hmisc)

标签: r string foreach multicore detect


【解决方案1】:

我猜循环不是并行执行的,因为您试图从所有线程中修改单个数组 (x)。

试试下面的方法,看看能不能解决你的问题

modifiedX = foreach(i = 1:length(y), .combine = c) %dopar%{

  stringCopy = x[i]

  if (sum(str_detect(x,paste("\\b",as.character(y),"\\b", sep=""))) > 0) {    
    str_replace(stringCopy, as.character (y[which(str_detect(x[i],paste("\\b",as.character(y),"\\b", sep="")) == TRUE)]), "")   
  }

  return(stringCopy)

}

print(modifiedX)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    相关资源
    最近更新 更多