r-foreach无法在函数内找到对象 [英] r - foreach unable to find object within function

查看:111
本文介绍了r-foreach无法在函数内找到对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a function defined below named algor, which is translated from MATLAB to R. In order to make the function faster, I am using the foreach construct for the first time. I have the complete function code below:

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,如下所示:

Although I have exported A, ybar, Ia, x, and y I am getting an error that the object A is not found, which is below:

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?

How do I get foreach to recognize the defined objects: A, ybar, Ia, x, and y?

谢谢.

推荐答案

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

Try defining the .GlobalEnv variables within the foreach loop in every call.

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

这篇关于r-foreach无法在函数内找到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆