“foreach”并行循环返回<na> s

时间:2015-10-12 12:36:45

标签: r foreach dataframe

我正在尝试并行处理多个列表项。

我的目标是:根据每个列的值运行一些标签功能。然后返回包含节点名称,列名称和已处理标签的数据框

使用普通的for循环,工作流程正常。但是,当我尝试在foreach循环中执行相同的操作时,返回的结果是 (请注意:以下只是原始数据集的抽象)

我不确定到底是什么搞砸了..如果你可以帮我把那件事搞砸了那就太棒了: - )

set.seed(12345)
options(stringsAsFactors = F)


# I. Random data generation (Original data is in data frame format)
random.data = list()
random.data[["one"]] = as.data.frame(matrix(data = runif(n = 15), ncol = 3))
random.data[["two"]] = as.data.frame(matrix(data = runif(n = 15), ncol = 3))
random.data[["three"]] = as.data.frame(matrix(data = runif(n = 15), ncol = 3))



# II. Some function applied to each column to label/classify the values
valslabel = function(DataCOlumn) {
  if(mean(DataCOlumn) < 0.5) return("low")
  return("high")
}



# III. Generating the desired output in a regular for loop : 

desiredOutput = list()

for(frame.i in seq_along(random.data)) {

  frame = random.data[[frame.i]]
  frame.name = names(random.data)[frame.i]
  frame.results = data.frame(frame.name = character(0), 
                  mappedField = character(0), label = character(0) )

  for(col.i in 1:ncol(frame)) {
    frame.results[col.i, "frame.name"] = frame.name
    frame.results[col.i, "mappedField"] = colnames(frame)[col.i]
    frame.results[col.i, "label"] = valslabel(frame[,col.i])  
  }

  desiredOutput[[frame.name]] = frame.results
}


print(desiredOutput)

# $one
# frame.name mappedField label
# 1        one          V1  high
# 2        one          V2  high
# 3        one          V3   low
# 
# $two
# frame.name mappedField label
# 1        two          V1   low
# 2        two          V2  high
# 3        two          V3   low
# 
# $three
# frame.name mappedField label
# 1      three          V1   low
# 2      three          V2  high
# 3      three          V3  high




# IV. Using the "foreach" parallel execution

library(foreach)
library(doParallel)

cl = makeCluster(6)
registerDoParallel(cl)

output = foreach(frame.i = seq_along(random.data), .verbose = T) %dopar% {

  frame = random.data[[frame.i]]
  frame.name = names(random.data)[frame.i]
  frame.results = data.frame(frame.name = character(0), mappedField = character(0), label = character(0) )

  for(col.i in 1:ncol(frame)) {
    frame.results[col.i, "frame.name"] = frame.name
    frame.results[col.i, "mappedField"] = colnames(frame)[col.i]
    frame.results[col.i, "label"] = valslabel(frame[,col.i])  
  }

  return(frame.results)
}


print(output)

# [[1]]
# frame.name mappedField label
# 1       <NA>        <NA>  <NA>
# 2       <NA>        <NA>  <NA>
# 3       <NA>        <NA>  <NA>
#   
# [[2]]
# frame.name mappedField label
# 1       <NA>        <NA>  <NA>
# 2       <NA>        <NA>  <NA>
# 3       <NA>        <NA>  <NA>
#   
# [[3]]
# frame.name mappedField label
# 1       <NA>        <NA>  <NA>
# 2       <NA>        <NA>  <NA>
# 3       <NA>        <NA>  <NA>

谢谢!

1 个答案:

答案 0 :(得分:3)

问题与您初始化数据框的方式有关,而且在foreach环境中,选项stringsAsFactors未设置为FALSE这一事实。每个foreach循环中发生的事情都是这样的

options(stringsAsFactors = FALSE)
d <- data.frame(x =character(0))
d[1, "x"] <- "a"
#Warning message:
#In `[<-.factor`(`*tmp*`, iseq, value = "a") :
#  invalid factor level, NA generated
d
#     x
#1 <NA>

请注意,这只会发出警告,而不是错误,因此循环不会停止。如果您首先将stringsAsFactors设置为FALSE则没有问题(就像您没有并行运行时那样)

options(stringsAsFactors = FALSE)
d <- data.frame(x =character(0))
d[1, "x"] <- "a"
d
#  x
#1 a

在您的全球环境中,您已设置options(stringsAsFactors = FALSE),因此%do%循环有效。但是,此选项不会在每个并行作业的本地环境中传递,因此%dopar%循环会遇到上述问题。

查看以下

输出的示例
options(stringsAsFactors = FALSE)
.Options$stringsAsFactors
#[1] FALSE
foreach(i = 1:3) %dopar% .Options$stringsAsFactors
#[[1]]
#[1] TRUE
#
#[[2]]
#[1] TRUE
#
#[[3]]
#[1] TRUE

因此解决方案是在stringsAsFactors = FALSE循环中设置选项foreach

顺便说一句,使用整个列向量而不是逐行逐行创建数据框要好得多。在您的示例中,您可以替换

frame.results = data.frame(frame.name = character(0), mappedField = character(0), label = character(0))
for(col.i in 1:ncol(frame)) {
    frame.results[col.i, "frame.name"] = frame.name
    frame.results[col.i, "mappedField"] = colnames(frame)[col.i]
    frame.results[col.i, "label"] = valslabel(frame[,col.i])  
}

frame.results <- data.frame( 
    frame.name = frame.name, 
    mappedField = colnames(frame), 
    label = valslabel1(colMeans(frame)))

其中valslabel函数已被矢量化版本替换

valslabel1 <- function(x) {
    ifelse(x < 0.5, "low", "high")
}