Foreach loop unable to find object

我们两清 提交于 2019-11-29 15:29:50
MrFlick

This sounds like a bad design. It's almost never necessary to use eval(parse()).

To get a variable, get() is somewhat safer, like get(bar.name)[rab]. But you're still running into an environment issue here. Since you don't have the variables bar or rab in the body of the dopar, they are not exported to the environment where foreach is running the code. You can fix that with an explicit assignment of the .export parameter of foreach to make sure those variables are exported. Here I change to use get and only have to explicitly export bar because rab is now include in the box of the function.

foo<-foreach(m = 1:10, .export=c("bar"), .packages = c("stats")) %dopar% {
  get(bar.name)[rab]
}

A better idea would be rather than specifying a variable name, specify an element of a named list. For example

baz <- list(bar=letters[1:4], bob=letters[5:7])

Then you could do

baz.name <- "bar"
rab <- c(2,4)

foo<-foreach(m = 1:10, .packages = c("stats")) %dopar% {
  baz[[baz.name]][rab]
}

And because dopar can see the variables baz, baz.name, and rab you don't have to export anything.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!