r-foreach无法在函数内找到对象

时间:2019-06-07 17:25:28

标签: r loops foreach

我有一个下面定义的名为algor的函数,该函数已从MATLAB转换为R。为了使该函数更快,我第一次使用foreach构造。我有下面的完整功能代码:

library("ramify")
library("foreach")

algor <- function (vc) {

# initialize A, ybar, and Ia
A <- 0

ybar <- 0

Ia <- 0

# x is the first column of vc   
x <- vc[, 1, drop = FALSE]

# y is the second column of vc  
y <- vc[, 2, drop = FALSE]

# n is the length of x
n <- length(x)

foreach(i = 1:(n-1), .combine = 'c', .export = c("A", "ybar", "Ia", "x", "y")) %do% {
        A <- A + 0.5 * (x[i] - x[i+1]) * (y[i] + y[i+1])
        ybar <- ybar + (1 / 6) * (x[i] - x[i+1]) * (y[i] ^ 2 + y[i] * y[i+1] + y[i+1] ^ 2)
        Ia <- Ia + (1 / 12) * (x[i] - x[i+1]) * (y[i] ^ 3 + y[i] ^ 2 * y[i+1] + y[i] * y[i+1] ^ 2 + y[i+1] ^ 3)
}

props <- mat("A, Ia, ybar", eval = TRUE)

return(props)
}


inner <- mat("0, 300; 300, 300; 300, 695; 0, 695; 0, 300")

algor(inner)

尽管我已经导出了A,ybar,Ia,x和y,但我收到一个错误,发现找不到对象A,如下所示:

Error in eval(parse(text = paste0("c(", paste0(char_vals, collapse = ","),  : 
  object 'A' not found
Called from: eval(parse(text = paste0("c(", paste0(char_vals, collapse = ","), 
    ")")))

如何获取foreach来识别已定义的对象:A,ybar,Ia,x和y?

谢谢。

1 个答案:

答案 0 :(得分:2)

尝试在每次调用的.GlobalEnv循环中定义foreach变量。

library("ramify")
library("foreach")

algor <- function (vc) {

  # initialize A, ybar, and Ia
  A <- 0

  ybar <- 0

  Ia <- 0

  # x is the first column of vc   
  x <- vc[, 1, drop = FALSE]

  # y is the second column of vc  
  y <- vc[, 2, drop = FALSE]

  # n is the length of x
  n <- length(x)

  foreach(i = 1:(n-1), .combine = 'c', .export = c("A", "ybar", "Ia", "x", "y")) %do% {
    .GlobalEnv$A <- A
    .GlobalEnv$ybar <- ybar
    .GlobalEnv$Ia <- Ia
    A <- A + 0.5 * (x[i] - x[i+1]) * (y[i] + y[i+1])
    ybar <- ybar + (1 / 6) * (x[i] - x[i+1]) * (y[i] ^ 2 + y[i] * y[i+1] + y[i+1] ^ 2)
    Ia <- Ia + (1 / 12) * (x[i] - x[i+1]) * (y[i] ^ 3 + y[i] ^ 2 * y[i+1] + y[i] * y[i+1] ^ 2 + y[i+1] ^ 3)
  }

  props <- mat("A, Ia, ybar", eval = TRUE)

  return(props)
}


inner <- mat("0, 300; 300, 300; 300, 695; 0, 695; 0, 300")

algor(inner)

这将返回:

       [,1]        [,2]     [,3]
[1,] 118500 30870237500 58953750