【问题标题】:r - foreach unable to find object within functionr - foreach 无法在函数中找到对象
【发布时间】:2019-10-23 05:26:50
【问题描述】:

我在下面定义了一个名为 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?

谢谢。

【问题讨论】:

    标签: r loops foreach


    【解决方案1】:

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

    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
    

    【讨论】:

    • 谢谢。那工作得很好。你知道在这个函数中设置全局环境变量是否会影响这个函数成为更大包的一部分?
    猜你喜欢
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 2018-08-29
    相关资源
    最近更新 更多